java-合并文件给出错误:文件结尾,预期行

我正在使用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)

解决方法:

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.

上一篇:安全模式下卸载windows installer打包的软件(转)


下一篇:Python __dict__属性详解