2010-08-27 76 views
49

我想很多PDF文件合併到使用PDFBox之一,這是我做了什麼:如何將兩個PDF文件合併到一個Java文件中?

PDDocument document = new PDDocument(); 
for (String pdfFile: pdfFiles) { 
    PDDocument part = PDDocument.load(pdfFile); 
    List<PDPage> list = part.getDocumentCatalog().getAllPages(); 
    for (PDPage page: list) { 
     document.addPage(page); 
    } 
    part.close(); 
} 
document.save("merged.pdf"); 
document.close(); 

哪裏pdfFiles是包含所有PDF文件的ArrayList<String>

當我運行上面,我總是得到:

org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor 

我做錯什麼了嗎?還有其他的方式嗎?

+1

有人指出的iText [http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html],然後刪除的答案。它的工作,並感謝。 – Lipis 2010-08-27 15:20:45

+0

[鏈接](http://java-x.blogspot.de/2006/11/merge-pdf-files-with-itext.html)可能會幫助有人尋找答案。 – 2013-09-27 13:15:00

回答

90

爲什麼不使用pdfbox的PDFMergerUtility

PDFMergerUtility ut = new PDFMergerUtility(); 
ut.addSource(...); 
ut.addSource(...); 
ut.addSource(...); 
ut.setDestinationFileName(...); 
ut.mergeDocuments(); 
+0

也可以,但我也在使用PDFBox來創建PDF。 – Lipis 2011-02-02 17:11:58

+0

它允許合併已掃描圖像的PDF和已寫入的PDF嗎? – 2015-03-03 08:07:19

+2

@RageshKr:據我瞭解,無論其內容如何,​​它都會合並任何PDF。 – cherouvim 2015-03-03 13:48:37

3
package article14; 

import java.io.File; 
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage; 
import org.apache.pdfbox.util.PDFMergerUtility; 

public class Pdf 
{ 
    public static void main(String args[]) 
    { 
     new Pdf().createNew(); 
     new Pdf().combine(); 
     } 

    public void combine() 
    { 
     try 
     { 
     PDFMergerUtility mergePdf = new PDFMergerUtility(); 
     String folder ="pdf"; 
     File _folder = new File(folder); 
     File[] filesInFolder; 
     filesInFolder = _folder.listFiles(); 
     for (File string : filesInFolder) 
     { 
      mergePdf.addSource(string);  
     } 
    mergePdf.setDestinationFileName("Combined.pdf"); 
    mergePdf.mergeDocuments(); 
     } 
     catch(Exception e) 
     { 

     } 
    } 

public void createNew() 
{ 
    PDDocument document = null; 
    try 
    { 
     String filename="test.pdf"; 
     document=new PDDocument(); 
     PDPage blankPage = new PDPage(); 
     document.addPage(blankPage); 
     document.save(filename); 
    } 
    catch(Exception e) 
    { 

    } 
} 

} 
+0

吞嚥異常是一種不好的模式。 catch(Exception e){ } – 2017-12-11 11:40:04

0

如果你想兩個文件,其中一個覆蓋其他聯合(例如:文件A是一個模板和文檔B有你想要把模板上的文字),這個工程:

打造「DOC」後,你想最重要的是寫你的模板(templateFile) -

PDDocument watermarkDoc = PDDocument.load(getServletContext() 
       .getRealPath(templateFile)); 
    Overlay overlay = new Overlay(); 

    overlay.overlay(watermarkDoc, doc); 
4

這是準備使用的代碼,從http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar合併4個PDF文件需要iText.jar,更多http://tutorialspointexamples.com/

import com.itextpdf.text.Document; 
import com.itextpdf.text.pdf.PdfContentByte; 
import com.itextpdf.text.pdf.PdfImportedPage; 
import com.itextpdf.text.pdf.PdfReader; 
import com.itextpdf.text.pdf.PdfWriter; 

/** 
* This class is used to merge two or more 
* existing pdf file using iText jar. 
*/ 
public class PDFMerger { 

static void mergePdfFiles(List<InputStream> inputPdfList, 
     OutputStream outputStream) throws Exception{ 
    //Create document and pdfReader objects. 
    Document document = new Document(); 
    List<PdfReader> readers = 
      new ArrayList<PdfReader>(); 
    int totalPages = 0; 

    //Create pdf Iterator object using inputPdfList. 
    Iterator<InputStream> pdfIterator = 
      inputPdfList.iterator(); 

    // Create reader list for the input pdf files. 
    while (pdfIterator.hasNext()) { 
      InputStream pdf = pdfIterator.next(); 
      PdfReader pdfReader = new PdfReader(pdf); 
      readers.add(pdfReader); 
      totalPages = totalPages + pdfReader.getNumberOfPages(); 
    } 

    // Create writer for the outputStream 
    PdfWriter writer = PdfWriter.getInstance(document, outputStream); 

    //Open document. 
    document.open(); 

    //Contain the pdf data. 
    PdfContentByte pageContentByte = writer.getDirectContent(); 

    PdfImportedPage pdfImportedPage; 
    int currentPdfReaderPage = 1; 
    Iterator<PdfReader> iteratorPDFReader = readers.iterator(); 

    // Iterate and process the reader list. 
    while (iteratorPDFReader.hasNext()) { 
      PdfReader pdfReader = iteratorPDFReader.next(); 
      //Create page and add content. 
      while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) { 
        document.newPage(); 
        pdfImportedPage = writer.getImportedPage(
          pdfReader,currentPdfReaderPage); 
        pageContentByte.addTemplate(pdfImportedPage, 0, 0); 
        currentPdfReaderPage++; 
      } 
      currentPdfReaderPage = 1; 
    } 

    //Close document and outputStream. 
    outputStream.flush(); 
    document.close(); 
    outputStream.close(); 

    System.out.println("Pdf files merged successfully."); 
} 

public static void main(String args[]){ 
    try { 
     //Prepare input pdf file list as list of input stream. 
     List<InputStream> inputPdfList = new ArrayList<InputStream>(); 
     inputPdfList.add(new FileInputStream("..\\pdf\\pdf_1.pdf")); 
     inputPdfList.add(new FileInputStream("..\\pdf\\pdf_2.pdf")); 
     inputPdfList.add(new FileInputStream("..\\pdf\\pdf_3.pdf")); 
     inputPdfList.add(new FileInputStream("..\\pdf\\pdf_4.pdf")); 


     //Prepare output stream for merged pdf file. 
     OutputStream outputStream = 
       new FileOutputStream("..\\pdf\\MergeFile_1234.pdf"); 

     //call method to merge pdf files. 
     mergePdfFiles(inputPdfList, outputStream);  
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
} 
+0

這個問題很清楚地被標記爲[tag:pdfbox]。您提出了[tag:itext]的解決方案。因此,你的答案是無關緊要的。 (也就是說,iText解決方案也是iText開發人員通常不推薦的一種,因爲它會丟失交互功能並忽略旋轉和頁面大小。) – mkl 2017-01-09 21:59:25

+0

然後標題應該是「如何將兩個PDF文件合併爲一個Java文件PdfBox「 – 2017-12-11 11:35:53

+0

此外iText帶有一個惡意的許可證。 – 2018-01-16 15:54:06

相關問題