我将使用PdfBox for android来向
PDF
文件追加数据。
要追加的数据
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)