简体   繁体   English

将PDF与iText 2.1.7合并会导致它们缩小

[英]Merging PDFs with iText 2.1.7 is causing them to shrink

I am using iText 2.1.7 to merge some document PDFs into a single PDF. 我正在使用iText 2.1.7将一些文档PDF合并为一个PDF。 The code below seems to work just fine, however it appears in some instances the rendered PDF is scaled slightly smaller, like at 90% of the PDF if printed directly before processing. 下面的代码似乎可以正常工作,但是在某些情况下,呈现的PDF会稍微缩小,例如,如果直接在处理前打印,则占PDF的90%。

Is there a way to keep the current size? 有没有办法保持当前大小?

private void doMerge(List<InputStream> list, OutputStream outputStream) throws DocumentException, IOException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfContentByte cb = writer.getDirectContent();

        for (InputStream in : list) {
            PdfReader reader = new PdfReader(in);
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                document.newPage();
                //import the page from source pdf
                PdfImportedPage page = writer.getImportedPage(reader, i);
                //add the page to the destination pdf
                cb.addTemplate(page, 0, 0);
            }
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    }

The API was already available with that version. 该版本已提供该API。 I would even suggest to use PdfSmartCopy instead of PdfCopy (or PdfCopyFields if form fields are inside). 我甚至会建议使用PdfSmartCopy代替PdfCopy (或PdfCopyFields如果表单域都在里面)。

private PdfSmartCopy copier;

public void SomeMainMethod(){

 Document finalPdf = new Document();
 copier = new PdfSmartCopy(finalPdf, outputstream);
 //Start adding pdfs
 finalPdf.open();

 //add n documents
 addDocuments(...);

 finalPdf.close();
 formCopier.close();
}

public void addDocument(InputStream pdfDocument, int startPage, int endPage){
 PdfReader reader= new PdfReader(pdfDocument);

 int startPage = 1;
 int endPage = reader.getNumberOfPages();

 for (int i = startPage; i <= endPage; i++) {
    copier.addPage(this.copier.getImportedPage(reader,i));
 }

 if(copier!=null){
 //Important: Free Memory!
    copier.flush();
    copier.freeReader(reader);
 }
 if (reader!=null) {
    reader.close();
    reader=null;
 }
 pdfDocument.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM