Java:需要从字节数组创建 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1777914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Need to create PDF from byte-Array
提问by AEIOU
From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF
out of it.
从 DB2 表中,我得到了 blob,我将其转换为字节数组,以便我可以使用它。我需要获取字节数组并从中创建一个PDF
。
This is what I have:
这就是我所拥有的:
static void byteArrayToFile(byte[] bArray) {
try {
// Create file
FileWriter fstream = new FileWriter("out.pdf");
BufferedWriter out = new BufferedWriter(fstream);
for (Byte b: bArray) {
out.write(b);
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
But the PDF
it creates is not right, it has a bunch of black lines running from top to bottom on it.
但是PDF
它创建的不对,它上面有一堆从上到下运行的黑线。
I was actually able to create the correct PDF
by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
我实际上能够PDF
通过使用基本相同的过程编写 Web 应用程序来创建正确的。Web 应用程序和 about 代码之间的主要区别在于这一行:
response.setContentType("application/pdf");
So I know the byte array is a PDF
and it can be done, but my code in byteArrayToFile
won't create a clean PDF
.
所以我知道字节数组是 aPDF
并且可以完成,但是我的代码byteArrayToFile
不会创建一个干净的PDF
.
Any ideas on how I can make it work?
关于如何使其工作的任何想法?
采纳答案by Jason Orendorff
Sending your output through a FileWriter
is corrupting it because the data is bytes, and FileWriter
s are for writing characters. All you need is:
通过 a 发送输出FileWriter
会损坏它,因为数据是字节,而FileWriter
s 用于写入字符。所有你需要的是:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
回答by dapc
One can utilize the autoclosable interface that was introduced in java 8.
可以利用 java 8 中引入的自动关闭接口。
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
回答by Singh Ss
Read from file or string to bytearray
.
从文件或字符串读取到bytearray
.
byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
// setting font family and font size
cs.beginText();
cs.setFont(PDType1Font.HELVETICA, 14);
cs.setNonStrokingColor(Color.BLACK);
cs.newLineAtOffset(20, 750);
for (String str: arrOfStr) {
cs.newLineAtOffset(0, -15);
cs.showText(str);
}
cs.newLine();
cs.endText();
}
document.save(znaFile);
document.close();