2016-10-03 27 views

回答

2

你可能想看看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(); 
     } 
    } 
} 
+0

您好,当我用局部图像路径是工作好吧,当我把图像在线路径(http://www.foodnavigator.com/var/plain_site/storage/images/publications/food-beverage-nutrition/foodnavigator.com/science-nutrition/high-cost-of-水果和蔬菜连接到高体脂肪中,年轻的孩子学习/ 8800391-3-ENG-GB /高性价比的水果和蔬菜连接到higher-体脂肪中,年轻的孩子-S tudy.jpg),那么它不会显示图像。请告诉我该怎么办。 – Manojkumar

+0

@Manojkumar请分享结果PDF。如果您的代码与上面的代码不同,请创建一个新问题。 –

+0

String imageUrls =“F:/me.png”; String imageUrls =“www.foodnavigator.com/var/plain_site/storage/images/publications/food-beverage-nutrition/foodnavigator.com/science-nutrition/high-cost-of-fruit-and-vegetables-linked-to - 更高的体脂肪,在年轻的子女学习/ 8800391-3-ENG-GB /高性价比的水果和蔬菜连接到高体脂肪中,年轻的孩子-Study.jpg“; PDImageXObject pdImage = PDImageXObject.createFromFile(imageUrls,document);contentStream.drawImage(pdImage,margin + 5,texty,170,100); – Manojkumar