0

我正在尝试将 2 个 pdf 合并为一个。合并工作正常,但内容从 pdf 页面溢出。A如附件所示。原始文件pdf如下。

合并前的原始文档

合并文档后是这样的 在此处输入图像描述

Java代码如下:

BaseFont bf = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED);
        //BaseFont bf= BaseFont.createFont();
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data
        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader,
                        pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                            + currentPageNumber + " of " + totalPages, 520,
                            5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

请帮忙。

4

2 回答 2

2

请下载我的书第 6 章并查看表 6.1。您在合并两个文档时犯了错误,使用PdfWriter而不是使用PdfCopy文档。查看清单 6.22 了解如何在使用PdfCopy.

于 2013-02-08T11:34:44.000 回答
1

我使用“PdfCopyFields”片段如下:

public static boolean concatPDFFiles(List<String> listOfFiles,
        String outputfilepath) throws FileNotFoundException, DocumentException {
    PdfCopyFields copy = null;
    try {
        copy = new PdfCopyFields(new FileOutputStream(outputfilepath));
    } catch (DocumentException ex) {
        Logger.getLogger(MergerGoogleDocsToPDF.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        for (String fileName : listOfFiles) {
            PdfReader reader1 = new PdfReader(fileName);
            copy.addDocument(reader1);
        }
    } catch (IOException ex) {
        Logger.getLogger(MergerGoogleDocsToPDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        copy.close();
    }
    if (new File(outputfilepath).exists()) {
        double bytes = new File(outputfilepath).length();
        //double kilobytes = (bytes / 1024);
        if (bytes != 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
于 2013-02-14T05:49:30.340 回答