2016-05-21 13 views
0

PDFBoxバージョン2.0.1を使用してPDFファイルにロゴを追加しようとしています。私は次のコードを持っています:Apache PDFbox Javaエラーが発生する読み込み入力ファイル

public class PDFService { 

    public void createPdf() { 
     // Create a document and add a page to it 
     PDDocument document = new PDDocument(); 

     PDPage page = new PDPage(); 

     document.addPage(page); 

     // Create a new font object selecting one of the PDF base fonts 
     PDFont font = PDType1Font.HELVETICA_BOLD; 

     ServletContext servletContext = (ServletContext) FacesContext 
       .getCurrentInstance().getExternalContext().getContext(); 

     try { 

      PDImageXObject pdImage = PDImageXObject.createFromFile(
        servletContext.getRealPath("/resources/images/logo.png"), 
        document); 

      PDPageContentStream contentStream = new PDPageContentStream(
        document, page); 

      contentStream.drawImage(pdImage, 20, 20); 

      contentStream.beginText(); 
      contentStream.setFont(font, 12); 
      contentStream.endText(); 

      // Make sure that the content stream is closed: 
      contentStream.close(); 

      // Save the results and ensure that the document is properly closed: 
      document.save("Hello World.pdf"); 
      document.close(); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

} 

エラーが発生しました:入力ファイルを読み込めません!ライン

PDImageXObject pdImage = PDImageXObject.createFromFile(
        servletContext.getRealPath("/resources/images/logo.png"), 
        document); 

中にServletContext.getRealPathによって返されるパスは、私がここで間違ってやっている何C:\Users\erickpezoa\Desktop\Multivision\Materials\apps\eclipse Kepler\eclipse\Projects\.metadata\.plugins\org.eclipse.core.resources\Servicios_Exequiales\build\weboutput\resources\images\logo.png

のですか?

+0

そのディレクトリに 'logo.png'がありますか? –

+0

はいロゴがあります – Erick

+0

@Erick ImageIO.read(新しいファイル(servletContext.getRealPath( "/ resources/images/logo.png")))) ' - を挿入するとどうなりますか? ?はいの場合、ファイルが結局そこにないことを意味します。 (別の時にチェックしたことがあるかもしれません)、または必要な権限がありません。 –

答えて

1

あなたはMavenとあなたのイメージフォルダを使用していることはsrc/Eclipseのメイン/リソース下にある場合、あなたは試すことができます:あなたはresourcesと呼ばれる別のフォルダを持っているsrc/main/resourcesの下であれば

PDImageXObject pdImage = PDImageXObject.createFromFile(
       PDFService.class.getResource("/images/logo.png").getPath(), 
       document); 

は唯一のパスとして/resources/images/logo.pngを必要とされています。 Mavenを使用していない場合、出力フォルダには/ resources/imagesが含まれています。その場合:

PDImageXObject pdImage = PDImageXObject.createFromFile(
       PDFService.class.getResource("/resources/images/logo.png").getPath(), 
       document); 

はそれがお役に立てば幸いです。

関連する問題