将JPG添加到PDF格式非常慢

时间:2013-05-28 15:28:55

标签: pdfbox

我正在尝试使用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();
        }
    }
}

1 个答案:

答案 0 :(得分: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();
    }