代码之家  ›  专栏  ›  技术社区  ›  Manojkumar

如何在PdfBox 2.0.3中显示图像?

  •  2
  • Manojkumar  · 技术社区  · 10 年前

    有人能给我举个例子,说明如何使用Apache PDFBox 2.0.3在PDF文件中显示图像吗?

    提前感谢

    1 回复  |  直到 6 年前
        1
  •  4
  •   mkl    10 年前

    你可能想看看 pdfbox examples directory in the Apache SVN repository ,特别是命名恰当的示例类 AddImageToPDF 使用这种关键方法:

    public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
            throws IOException
    {
        // the document
        PDDocument doc = null;
        try
        {
            doc = PDDocument.load( new File(inputFile) );
    
            //we will add the image to the first page.
            PDPage page = doc.getPage(0);
    
            // createFromFile is the easiest way with an image file
            // if you already have the image in a BufferedImage, 
            // call LosslessFactory.createFromImage() instead
            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
    
            // contentStream.drawImage(ximage, 20, 20 );
            // better method inspired by http://stackoverflow.com/a/22318681/535646
            // reduce this value if the image is too large
            float scale = 1f;
            contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);
    
            contentStream.close();
            doc.save( outputFile );
        }
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
    }