2016-10-03 67 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