2011-04-12 69 views
0

我正在嘗試使用以下庫導入com.itextpdf以便從一個pdf文檔中獲取|: 每頁創建一個新的pdf文檔。在不同pdf頁面中拆分pdf

例如,對於a.pdf這是3頁我創造a1.pdf a2.pdf和a3.pdf其中A1是的等第一頁......

由於種種原因產生的輸出不正確。如果a.pdf是一個頁面不同的哈希創建新的網頁...任何幫助表示讚賞

public static void onePage(int num, String to, PdfReader reader) throws DocumentException,IOException { 
    Document document = new Document(PageSize.A4); 

    PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(to)); 
    document.open(); 

    PdfImportedPage page; 
    page = writer.getImportedPage(reader, num); 
    Image instance = Image.getInstance(page); 

    instance.setAbsolutePosition(0, 30); 

    document.add(instance); 

    document.close(); 

} 
public static void makePages(String name) throws IOException, DocumentException{ 

    PdfReader reader = new PdfReader(name+".pdf"); 
    int n = reader.getNumberOfPages(); 
    for(int i=1; i<=n;i++){ 
     onePage(i, name+i+".pdf", reader); 
    } 
} 

回答

0

,你可以檢查是否有網頁,如果一個頁面只有在那裏,你並不需要創建新的PDF。是嗎?這將是簡單的問題修復

1

兩個PDF的散列最有可能只是不同,因爲PDF文檔包含很多額外的元數據,當您將單個頁面複製到新的PDF時可能不會被相同地複製。這可能與關於何時生成PDF的信息一樣微不足道。如果只有一個頁面,最簡單的事情就是簡單地不分割PDF。

+0

我給了一個頁面的例子,但相當多,我們有30頁的PDF我們可以分成30 1頁的文件,由於某些原因創建的文件不是「正確的」 – Cedric 2011-04-13 12:36:50

+0

嗯......不幸的是,我不是非常熟悉iText知道w這個問題可能是。我只是誤解了你的問題。 – Michael 2011-04-15 21:18:43

1

使用PDFBox將PDF頁轉換爲單個頁面。從Apache PDFBox latest releases

下載PDFBox的罐子,

下面的Java程序執行支持的罐子pdfbox-1.8.3.jarcommons-logging-1.1.3.jar

import java.io.File; 
import java.util.List; 

import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage; 
/** 
* 
* @author udaykiran.pulipati 
* 
*/ 

@SuppressWarnings("unchecked") 
public class ExtractPagesFromPdfAndSaveAsNewPDFPage { 
    public static void main(String[] args) { 
     try { 
      String sourceDir = "C:/PDFCopy/04-Request-Headers.pdf"; 
      String destinationDir = "C:/PDFCopy/"; 
      File oldFile = new File(sourceDir); 
      String fileName = oldFile.getName().replace(".pdf", ""); 
      if (oldFile.exists()) { 
       File newFile = new File(destinationDir); 
       if (!newFile.exists()) { 
        newFile.mkdir(); 
      } 

      PDDocument document = PDDocument.load(sourceDir); 
      List<PDPage> list = document.getDocumentCatalog().getAllPages(); 

      int pageNumber = 1; 
      for (PDPage page : list) { 
       PDDocument newDocument = new PDDocument(); 
       newDocument.addPage(page); 

       newFile = new File(destinationDir + fileName + "_"+ pageNumber +".pdf"); 
       newFile.createNewFile(); 

       newDocument.save(newFile); 
       newDocument.close(); 
       pageNumber++; 
      } 
     } else { 
      System.err.println(fileName +" File not exists"); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

}