0

我正在尝试使用 PDFBox 将图像写入 PDF。我正在使用他们的样本(如附件)。一切都很好,但是写入 3.5MB jpeg (3200*2500px) 大约需要 2 秒。

这是正常的吗?有什么方法可以让它更快(至少 10 倍)?

public void createPDFFromImage( String inputFile, String image, String outputFile ) 
    throws IOException, COSVisitorException
{
    // the document
    PDDocument doc = null;
    try
    {
        doc = PDDocument.load( inputFile );

        //we will add the image to the first page.
        PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );

        PDXObjectImage ximage = null;
        if( image.toLowerCase().endsWith( ".jpg" ) )
        {
            ximage = new PDJpeg(doc, new FileInputStream( image ) );
        }
        else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
        {
            ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
        }
        else
        {
            //BufferedImage awtImage = ImageIO.read( new File( image ) );
            //ximage = new PDPixelMap(doc, awtImage);
            throw new IOException( "Image type not supported:" + image );
        }
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        contentStream.drawImage( ximage, 20, 20 );

        contentStream.close();
        doc.save( outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}
4

1 回答 1

0

如果您愿意使用其他产品itext可能会非常快,请查看http://tutorials.jenkov.com/java-itext/image.html。就个人而言,我使用 +750k jpg 图像进行了此测试并拍摄了78 毫秒

try {
        PdfWriter.getInstance(document,
                new FileOutputStream("Image2.pdf"));
        document.open();

        long start = System.currentTimeMillis();
        String imageUrl = "c:/Users/dummy/notSoBigImage.jpg";
        Image image = Image.getInstance((imageUrl));
        image.setAbsolutePosition(500f, 650f);
        document.add(image);

        document.close();
        long end = System.currentTimeMillis() - start;
        System.out.println("time: " + end + " ms");
    } catch(Exception e){
        e.printStackTrace();
    }
于 2013-05-28T15:51:27.567 回答