简体   繁体   English

JAVA 合并 2 PDF 字节 arrays

[英]JAVA Merge 2 PDF byte arrays

I receive two PDFs, each as a byte array.我收到两个 PDF,每个都是一个字节数组。 So now I have 2 arrays, a[] and b[].所以现在我有 2 个 arrays、a[] 和 b[]。 I concatenate them and save them to c[].我将它们连接起来并将它们保存到 c[]。 When I convert c[] to a PDF, only the 2nd file shows up.当我将 c[] 转换为 PDF 时,只显示第二个文件。 When I check the length of c[], it is len(a[]) + len(b[]).当我检查 c[] 的长度时,它是 len(a[]) + len(b[])。

I found other questions about this for different programming languages, and they say that I can't just concatenate them like this, we need to use a PDF authoring library.我发现了其他关于不同编程语言的问题,他们说我不能像这样连接它们,我们需要使用 PDF 创作库。 Since I receive byte arrays to begin with, is there anything else that could work in my situation?由于我收到字节 arrays 开始,在我的情况下还有什么可以工作的吗?

You can't just concatenate the byte arrays.您不能只连接字节 arrays。

You can find a couple of solutions for merging PDF files here How to merge two PDF files into one in Java?您可以在此处找到一些用于合并 PDF 文件的解决方案如何在 Java 中将两个 PDF 文件合并为一个?

If you have the PDF files, you can just use PDFMergerUtility of pdfbox.如果你有 PDF 文件,你可以使用 pdfbox 的 PDFMergerUtility。

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

If the PDF files are not available, you can just use the other solution with itext如果 PDF 文件不可用,您可以使用 itext 的其他解决方案

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.");
   }

}

If anyone still looking for such solution, try this:如果有人仍在寻找这样的解决方案,试试这个:

//Suppose we want to merge one pdf with another main pdf //假设我们要将一个 pdf 与另一个主 pdf 合并

          InputStream is1 = null;



          if (file1 != null) {

                 FileInputStream fis1 = new FileInputStream(file1);

                 byte[] file1Data = new byte[(int) file1.length()];

                 fis1.read(file1Data);

                 is1 = new java.io.ByteArrayInputStream(file1Data);

          }



          //

          InputStream mainContent = <ur main content>



          org.apache.pdfbox.pdmodel.PDDocument mergedPDF = new org.apache.pdfbox.pdmodel.PDDocument();

          org.apache.pdfbox.pdmodel.PDDocument mainDoc = org.apache.pdfbox.pdmodel.PDDocument.load(mainContent);

          org.apache.pdfbox.multipdf.PDFMergerUtility merger = new org.apache.pdfbox.multipdf.PDFMergerUtility();



          merger.appendDocument(mergedPDF, mainDoc);



          PDDocument doc1 = null;



          if (is1 != null) {

                 doc1 = PDDocument.load(is1);

                 merger.appendDocument(mergedPDF, doc1);

                //1st file appended to main pdf");

          }

         



          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          mergedPDF.save(baos);

//Now either u save it here or convert into InputStream if u want //现在要么你把它保存在这里,要么如果你想转换成 InputStream

          ByteArrayInputStream mergedInputStream = new ByteArrayInputStream(baos.toByteArray());

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

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