创建pdf并与pdfbox合并

use*_*884 4 java pdf merge 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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 13

您只需要使用该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
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你:)这个输入OutputStream转换的东西真的让我很累:(。谢谢! (2认同)

小智 10

我使用它来合并一些文档(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());
Run Code Online (Sandbox Code Playgroud)