2013-02-08 46 views
0

我正在嘗試合併2個PDF。合併工作正常,但內容從pdf頁面溢出。附件中顯示。原始文檔pdf如下。Itext pdf合併:pdf(文本截斷)頁面外的文檔溢出並且不顯示

Original Doc before merge

合併後文檔快到這樣 enter image description here

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; 
     } 

請幫助。

+0

原來的或目標的PDf的一些變焦屬性?? – zytham

+0

您使用'PdfWriter'而不是'PdfCopy',而忽略導入頁面的尺寸。因此,在他的回答中(按照原樣複製頁面)或者(如果前者由於調用方法的軟件的不當設計而不可行),請按照Bruno的建議採取導入頁面的**所有**頁面尺寸數據通過創建所需大小的頁面或縮放導入的頁面來實現。 – mkl

回答

2

請下載chapter 6 of my book並查看錶6.1。按照記錄,您在使用PdfWriter合併兩個文檔而不是使用PdfCopy時出錯。看看清單6.22,瞭解如何在使用PdfCopy時添加頁碼。

+1

+1;我想知道爲什麼這麼多人首先找到錯誤的例子... – mkl

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; 
    } 
}