with tutorial pdfmergerutility java pdf merge pdfbox

java - tutorial - pdfmergerutility



Crear pdf y combinar con pdfbox (3)

Solo necesita usar el PdfMergeUtility.addSource(InputStream) para agregar el origen de un inputstream y no de un archivo físico.

Con un rápido vistazo a la API, lo que podrías hacer es usar el PDDocument.save(OutputStream) para escribir el archivo en una matriz de bytes en la memoria, algo así debería funcionar.

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 }

Esto es lo que quiero hacer:

  1. Haga 2 archivos pdf diferentes usando pdfbox

  2. Combine estos dos archivos usando pdfmerger

Sé cómo hacer esto si estoy guardando el # 1 en el disco duro local del lado del servidor y cargando los archivos para el # 2. Pero lo que quiero hacer es usar "directamente de la memoria". He buscado todos los métodos desde este pdfboxes pero todavía no pude encontrarlo.

Este es mi código que obtiene del archivo local

Gracias.

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:[email protected]">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(); } } }


Utilizo esto para combinar algunos documentos (InputStreams) y escribir el documento fusionado en un 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());


Puede usar de esta manera también:
1) Crear lista de InputStream
2) Crear una instancia de la clase PDFMergerUtility
3) Establecer flujo de salida de destino
4) Agregue todos los InputStreams a PDFMerger como archivos de origen que deben fusionarse.
5) Combine los documentos llamando a " 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");