Vaadin转换并以PDF格式显示图像

时间:2016-10-20 11:01:17

标签: java pdf itext vaadin image-conversion

有谁知道如何将图像文件轻松转换为PDF格式。我需要的是从数据库中获取图像并将其作为PDF显示在屏幕上。我究竟做错了什么?我尝试使用iText但没有结果。 我的代码:

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 个答案:

答案 0 :(得分:1)

您没有正确使用iText:

  1. 您永远不会关闭您的作家,因此图像的添加永远不会写入输出流。

  2. 您将空字符串传递给FileOutputStream。如果要将pdf保留在内存中,请使用ByteArrayOutputStream。如果没有,请改为定义临时名称。

  3. 您将Document对象(特定于iText的对象)传递给Embedded对象,并将其视为文件。它不是pdf文件或byte []。您可能希望将ByteArrayOutputStream传递给ByteArrayOutputStream或将临时文件作为Embedded读入内存并将其传递给After the sleep, call drawAll(g). The drawAll method will print the following on the screen in black at position x=10 and y = 15: Project 2 by YOURNAME. Replace YOURNAME with your full name.

答案 1 :(得分: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;
}