我使用PdfBox for android将数据附加到public byte [] prerparePdfToAppend() {
final PDDocument document = new PDDocument();
final PDPage sourcePage = new PDPage();
document.addPage(sourcePage);
PDPageContentStream contentStream = new PDPageContentStream(document, sourcePage);
contentStream.beginText();
contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.showText("Name: " + firstName + " " + lastName);
contentStream.newLine();
...
contentStream.endText();
contentStream.close();
output = new ByteArrayOutputStream();
document.save(output);
document.close();
byte [] bytesToAppend = new byte[output.size()];
output.write(bytes);
output.close();
return bytesToAppend;
}
文件。
要追加的数据
public void merge (String assetFileName) {
byte [] toAppendPdf = prerparePdfToAppend();
PDFMergerUtility mergerUtility = new PDFMergerUtility();
mergerUtility.addSource(PDFBoxResourceLoader.getStream(assetFileName));
mergerUtility.addSource(new ByteArrayInputStream(toAppendPdf));
mergerUtility.setDestinationStream(destStream);
mergerUtility.mergeDocuments(); //IOException
}
合并代码(简化)
java.io.IOException: Error: End-of-File, expected line
at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1419)
at org.apache.pdfbox.pdfparser.COSParser.parseHeader(COSParser.java:1648)
at org.apache.pdfbox.pdfparser.COSParser.parsePDFHeader(COSParser.java:1627)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:348)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:888)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:802)
at org.apache.pdfbox.multipdf.PDFMergerUtility.mergeDocuments(PDFMergerUtility.java:172)
例外
{{1}}
答案 0 :(得分:4)
prerparePdfToAppend方法的最后几行对我来说很奇怪。但为什么让你的生活变得复杂?返回PDDocument:
public PDDocument prerparePdfToAppend()
{
final PDDocument document = new PDDocument();
final PDPage sourcePage = new PDPage();
document.addPage(sourcePage);
PDPageContentStream contentStream = new PDPageContentStream(document, sourcePage);
contentStream.beginText();
contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.showText("Name: " + firstName + " " + lastName);
contentStream.newLine();
...
contentStream.endText();
contentStream.close();
return document;
}
您的合并代码将如下所示:
public void merge (String assetFileName)
{
PDFMergerUtility mergerUtility = new PDFMergerUtility();
PDDocument srcDoc = PDDocument.load(PDFBoxResourceLoader.getStream(assetFileName));
PDDocument dstDoc = prerparePdfToAppend();
mergerUtility.appendDocument(dstDoc, srcDoc);
dstDoc.save(destStream);
srcDoc.close();
dstDoc.close();
}
如果这不起作用 - 请确保
PDFBoxResourceLoader.getStream(assetFileName)
真的是真正的PDF流。如果它仍然不起作用,请提及此新代码的哪一行产生异常。当然,请确保您使用的是最新版本的PDFBox。