Create pdf and merge with pdfbox

后端 未结 4 984
眼角桃花
眼角桃花 2021-02-10 16:03

This is what I want to do:

  1. Make 2 different pdf files using pdfbox

  2. Merge these two files together using pdfmerger

I know how

4条回答
  •  太阳男子
    2021-02-10 16:07

    You just need to use the PdfMergeUtility.addSource(InputStream) method to add source from an inputstream and not from a physical file.

    With a quick glance at the API, what you could do is use the PDDocument.save(OutputStream) method to write the file into a byte array in memory, something like this should work.

    static byte[] doIt(String message) {
       PDDocument doc = new PDDocument();
       // add the message
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       doc.save(baos);
       return baos.toByteArray();
    }
    
    void main(String args[]) {
       byte[] pdf1 = doIt("hello");
       byte[] pdf2 = doIt("world");
       PDFMergerUtility merger = new PDFMergerUtility();
       merger.addSource(new ByteArrayInputStream(pdf1));
       merger.addSource(new ByteArrayInputStream(pdf2));
       // do the rest with the merger
    }
    

提交回复
热议问题