簡體   English   中英

創建pdf並與pdfbox合並

[英]Create pdf and merge with pdfbox

這就是我想做的:

  1. 使用pdfbox制作2個不同的pdf文件

  2. 使用pdfmerger將這兩個文件合並在一起

如果將#1保存到服務器端本地硬盤並加載#2的文件,我知道該怎么做。 但是我想做的是“直接從內存中使用”。 我已經從此pdfbox中搜索了所有方法,但仍然找不到它。

這是我的代碼從本地文件中獲取

謝謝。

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.util.PDFMergerUtility;

/**
* This is an example that creates a simple document
* with a ttf-font.
*
* @author <a href="mailto:m.g.n@gmx.de">Michael Niedermair</a>
* @version $Revision: 1.2 $
*/
public class Test2
{

    /**
    * create the second sample document from the PDF file format specification.
    *
    * @param file     The file to write the PDF to.
    * @param message    The message to write in the file.
    * @param fontfile  The ttf-font file.
    *
    * @throws IOException If there is an error writing the data.
    * @throws COSVisitorException If there is an error writing the PDF.
    */
    public void doIt(final String file, final String message) throws IOException, COSVisitorException
    {

        // the document
        PDDocument doc = null;
        try
        {
            doc = new PDDocument();

            PDPage page = new PDPage();
            doc.addPage(page);
            PDFont font = PDType1Font.HELVETICA_BOLD;


            PDPageContentStream contentStream = new PDPageContentStream(doc, page);
            contentStream.beginText();
            contentStream.setFont(font, 12);
            contentStream.moveTextPositionByAmount(100, 700);
            contentStream.drawString(message);
            contentStream.endText();
            contentStream.close();

            doc.save(file);

            System.out.println(file + " created!");
        }
        finally
        {
            if (doc != null)
            {
                doc.close();
            }
        }
    }

    /**
     * This will create a hello world PDF document
     * with a ttf-font.
     * <br />
     * see usage() for commandline
     *
     * @param args Command line arguments.
     */
    public static void main(String[] args)
    {

        Test2 app = new Test2();
        Test2 app2 = new Test2();
        try {
            app.doIt("C:/here.pdf", "hello");
            app2.doIt("C:/here2.pdf", "helloagain");
            PDFMergerUtility merger = new PDFMergerUtility();
            merger.addSource("C:/here.pdf");
            merger.addSource("C:/here2.pdf");
            OutputStream bout2 = new BufferedOutputStream(new FileOutputStream("C:/hereisthefinal.pdf"));

            merger.setDestinationStream(bout2);
            merger.mergeDocuments();

        } catch (COSVisitorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

您只需要使用PdfMergeUtility.addSource(InputStream)方法從輸入流而不是物理文件添加源。

快速瀏覽一下API,您可以執行以下操作:使用PDDocument.save(OutputStream)方法將文件寫入內存中的字節數組中,這應該可以工作。

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
}

我用它來合並一些文檔(InputStreams)並將合並后的文檔寫在HttpServletResponse中。

  PDFMergerUtility mergedDoc = new PDFMergerUtility();
  ByteArrayOutputStream colDocOutputstream = new ByteArrayOutputStream();

  for (int i = 0; i < documentCount; i++)
  {
    ByteArrayOutputStream tempZipOutstream = new ByteArrayOutputStream();
...
    mergedDoc.addSource(new ByteArrayInputStream(tempZipOutstream.toByteArray()));
  }

  mergedDoc.setDestinationStream(colDocOutputstream);
  mergedDoc.mergeDocuments();

  response.setContentLength(colDocOutputstream.size());
  response.setContentType("application/pdf");
  response.setHeader("Content-Disposition", "attachment; filename=mergedDocument.pdf");
  response.setHeader("Pragma", "public");
  response.setHeader("Cache-Control", "max-age=0");
  response.addDateHeader("Expires", 0);
  response.getOutputStream().write(colDocOutputstream.toByteArray());

您也可以使用這種方式:-
1)創建InputStream列表
2)實例化PDFMergerUtility類
3)設置目標輸出流
4)將所有InputStreams添加為PDFMerger作為需要合並的源文件。
5)通過調用“ PDFmerger.mergeDocuments(); ”合並文檔

   List<InputStream> locations=new ArrayList<InputStream>();
        locations.add(new FileInputStream("E:/Filenet Project Support/MergePDFs_Sample_Code/Attorney_new_form.pdf"));
        locations.add(new FileInputStream("E:/Filenet Project Support/MergePDFs_Sample_Code/JH.pdf"));
        locations.add(new FileInputStream("E:/Filenet Project Support/MergePDFs_Sample_Code/Interpreter_new_form.pdf"));
        //Instantiating PDFMergerUtility class
        PDFMergerUtility PDFmerger = new PDFMergerUtility();
        //Setting Destination Output Stream
        OutputStream out = new FileOutputStream("E:/Filenet Project Support/MergePDFs_Sample_Code/merged.pdf");
        //Adding all InputStreams to PDFMerger as Source files which needs to be merged.
        PDFmerger.addSources(locations);
        //Setting Destination Output Stream
        PDFmerger.setDestinationStream(out);
        //Merging the two documents
        PDFmerger.mergeDocuments();
        System.out.println("Documents merged");

使用REST和PDFBOX

@RequestMapping(value = "/getMergePdf", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getMergePdf(@RequestParam(value = "filePath", required = true) String filePath,
            @RequestParam(value = "newFileName", required = true) String newFileName) throws IOException {

            // Step 1: Loading an Existing PDF Document
        File file = new File(filePath);
        File[] listFile = file.listFiles();

        // Step 2: Instantiating the PDFMergerUtility class
        PDFMergerUtility mergePdf = new PDFMergerUtility();

        // Step 3: Setting the source files
        for (File pdfName : listFile) {
            mergePdf.addSource(pdfName);
        }

        // Step 4: Setting the destination file
        ByteArrayOutputStream pdfDocOutputstream = new ByteArrayOutputStream();
        mergePdf.setDestinationFileName(newFileName + ".pdf");
        mergePdf.setDestinationStream(pdfDocOutputstream);
        mergePdf.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());

        // Step 5: write in Response
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);

        // Here you have to set the actual filename of your pdf
        headers.setContentDispositionFormData(mergePdf.getDestinationFileName(), mergePdf.getDestinationFileName());
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<>(pdfDocOutputstream.toByteArray(), headers, HttpStatus.OK);
        return response;


    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM