Create pdf and merge with pdfbox

后端 未结 4 980
眼角桃花
眼角桃花 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 16:20

    Using REST and PDFBOX

    @RequestMapping(value = "/getMergePdf", method = RequestMethod.GET)
        public ResponseEntity 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 response = new ResponseEntity<>(pdfDocOutputstream.toByteArray(), headers, HttpStatus.OK);
            return response;
    
    
        }
    

提交回复
热议问题