2016-10-20 58 views
0

有誰知道如何將圖像文件輕鬆轉換爲PDF格式。我需要的是從數據庫中獲取圖像並將其作爲PDF顯示在屏幕上。我究竟做錯了什麼?我試圖使用iText,但沒有結果。 我的代碼:Vaadin轉換並顯示圖像爲PDF

StreamResource resource = file.downloadFromDatabase();//get file from db 
Document converToPdf=new Document();//Create Document Object 
PdfWriter.getInstance(convertToPdf, new FileOutputStream(""));//Create PdfWriter for Document to hold physical file 
convertToPdf.open(); 
Image convertJpg=Image.getInstance(resource); //Get the input image to Convert to PDF 
convertToPdf.add(convertJpg);//Add image to Document 
Embedded pdf = new Embedded("", convertToPdf);//display document 
pdf.setMimeType("application/pdf"); 
pdf.setType(Embedded.TYPE_BROWSER); 
pdf.setSizeFull(); 

謝謝。

+2

分割的兩個步驟。 PDF是否正確生成?顯示它。 (但是爲什麼要通過PDF來顯示圖像,直接顯示圖像會更有效 –

+0

爲什麼要將圖像轉換成PDF?這需要一些用戶安裝PDF程序。當然,將圖像顯示爲 –

+0

Chris,問題在於當我用Vaadin顯示圖像時 - 它的大小(比例)總是依賴於瀏覽器,Firefox在窗口寬度內呈現圖像,而Chrome顯示的圖像與比屏幕尺寸更大,更寬,但是我需要確保圖像總是以全屏顯示,並且不會被瀏覽器切斷。 – Lena

回答

1

你沒有正確利用iText:

  1. 你永遠閉上你的作家,因此圖像的除了永遠不會被寫入OutputStream。

  2. 您將一個空字符串傳遞給您的FileOutputStream。如果要將pdf保存在內存中,請使用ByteArrayOutputStream。如果不是,請定義臨時名稱。

  3. 將您的Document對象(這是一個iText特定對象)傳遞給您的Embedded對象,並將其視爲文件。它不是pdf文件或字節[]。您可能需要傳遞ByteArrayOutputStream或將臨時文件作爲ByteArrayOutputStream讀入內存並將其傳遞至Embedded

0

也許有人會用(Vaadin + iText的)

Button but = new Button("FV"); 

    StreamResource myResource = getPDFStream(); 
    FileDownloader fileDownloader = new FileDownloader(myResource); 
    fileDownloader.extend(but); 

    hboxBottom.addComponent(but); 


private StreamResource getPDFStream() { 
    StreamResource.StreamSource source = new StreamResource.StreamSource() { 

     public InputStream getStream() { 

      // step 1 
     com.itextpdf.text.Document document = new com.itextpdf.text.Document(); 
     // step 2 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

      try { 
       com.itextpdf.text.pdf.PdfWriter.getInstance(document, baos); 

       // step 3 
       document.open(); 

       document.add(Chunk.NEWLINE); //Something like in HTML :-) 

       document.add(new Paragraph("TEST")); 


       document.add(Chunk.NEWLINE); //Something like in HTML :-)        

       document.newPage();   //Opened new page 

       //document.add(list);   //In the new page we are going to add list 

       document.close(); 

       //file.close(); 

       System.out.println("Pdf created successfully.."); 




      } catch (DocumentException ex) { 
       Logger.getLogger(WndOrderZwd.class.getName()).log(Level.SEVERE, null, ex); 
      } 

      ByteArrayOutputStream stream = baos; 
      InputStream input = new ByteArrayInputStream(stream.toByteArray()); 
       return input; 

     } 
    }; 
    StreamResource resource = new StreamResource (source, "test.pdf"); 
    return resource; 
}