2013-05-28 69 views
0

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

这是正常的吗?有什么办法可以让它更快(至少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(); 
     } 
    } 
} 
+0

我看过1.8源代码,时间用在ImageIO.read()中。图像被读取一次以获得图像信息(例如大小),这就是为什么。 –

回答

0

如果您愿意使用其他产品iText的可以去真快,看看http://tutorials.jenkov.com/java-itext/image.html .Personally,我做了这个测试用+ 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(); 
    } 
+0

谢谢,我们目前也在评估这个选项。 –