[英]Java: Need to create PDF from byte-Array
從 DB2 表中,我得到了 blob,我將其轉換為字節數組,以便我可以使用它。 我需要取出字節數組並從中創建一個PDF
。
這就是我所擁有的:
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());
}
}
但是它創建的PDF
不正確,它上面有一堆從上到下運行的黑線。
我實際上能夠通過使用基本相同的過程編寫 Web 應用程序來創建正確的PDF
。 Web 應用程序和 about 代碼之間的主要區別在於這一行:
response.setContentType("application/pdf");
所以我知道字節數組是一個PDF
並且可以完成,但是我在byteArrayToFile
代碼不會創建一個干凈的PDF
。
關於如何使其工作的任何想法?
通過FileWriter
發送輸出會破壞它,因為數據是字節,而FileWriter
s 用於寫入字符。 所有你需要的是:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
可以利用 java 7 中引入的自動關閉接口。
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
從文件或字符串讀取到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();
public static String getPDF() throws IOException {
File file = new File("give complete path of file which must be read");
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;enter code here
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
System.out.println("it came back"+baos);
byte[] buffer1= baos.toByteArray();
String fileName = "give your filename with location";
//stream.close();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer1);
return fileName;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.