Generate a pdf

I need to generate a pdf from a few variables and I can not do.
In the book is a reference to this
https://vaadin.com/book/vaadin7/-/page/advanced.printing.html#advanced.printing.pdf
but there is a class that does not find reference
FopFactory FopFactory.newInstance fopFactory = (); .
And the demo does not work
http://demo.vaadin.com/book-examples-vaadin7/book/#advanced.printing.pdfgeneration.
In the blog of Jamie Craane’s http://jcraane.blogspot.com.ar/2010/09/printing-in-vaadin.html ago freference a code of gogle code that does not exist.

Hi,
FopFactory is contained in Apache FOP project
http://xmlgraphics.apache.org/fop/
.

In my project I’m using
https://github.com/flyingsaucerproject/flyingsaucer
in combination with IText library. I’m using Freemarker templates to generate HTML code and after that I’m using flyingsaucer to generate PDF document from HTML.

I hope this will help you.

Sorry
Thanks but I can not get to understand need someone I can pass a simple example

Here is simple example using Apache FOP.

@Theme("mytheme")
@SuppressWarnings("serial")
public class MyVaadinUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "org.vaadin.fop.AppWidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);
        
        // Create the PDF source
        StreamSource source = new PdfSource();

        // Create the stream resource and give it a file name
        String fileName = System.currentTimeMillis() + ".pdf";
        StreamResource resource = new StreamResource(source, fileName);

        // These settings are not usually necessary. MIME type
        // is detected automatically from the file name, but
        // setting it explicitly may be necessary if the file
        // suffix is not ".pdf".
        resource.setMIMEType("application/pdf");
        resource.getStream().setParameter("Content-Disposition",
                "attachment; filename=" + fileName);
        
        
        Button button = new Button("Download PDF");
        layout.addComponent(button);
        
        // Extend the print button with an opener
        // for the PDF resource
        BrowserWindowOpener opener = new BrowserWindowOpener(resource);
        opener.extend(button);

        
        
        
    }

    public class PdfSource implements StreamSource {

        private FopFactory fopFactory = FopFactory.newInstance();
        private TransformerFactory tFactory = TransformerFactory.newInstance();

        private ByteArrayOutputStream bof;

        public PdfSource() {
            bof = new ByteArrayOutputStream();
            try {
                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, bof);
                Transformer transformer = tFactory.newTransformer();            
                InputStream foFile = MyVaadinUI.class.getClassLoader().getResourceAsStream("/readme.fo");
                Source src = new javax.xml.transform.stream.StreamSource(foFile);
                Result res = new SAXResult(fop.getDefaultHandler());
                transformer.transform(src, res);
                bof.flush();
            } catch (FOPException e) {
                e.printStackTrace();
            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public InputStream getStream() {
            return new ByteArrayInputStream(bof.toByteArray());
        }

    }

}

For this to work you need to add in your pom.xml

<dependency>
            <groupId>org.apache.xmlgraphics</groupId>
            <artifactId>fop</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.avalon.framework</groupId>
            <artifactId>avalon-framework-api</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.avalon.framework</groupId>
            <artifactId>avalon-framework-impl</artifactId>
            <version>4.3.1</version>
        </dependency>

Also, in this example I’m using sample fo file from

http://svn.apache.org/viewvc/xmlgraphics/fop/tags/fop-1_1/examples/fo/basic/readme.fo?view=co

While this solution is working, I prefer to use Flyingsaucer, iText and FreeMarker.

Excellent I will try to use

If you have HTML, we use wkhtmltopdf:
http://wkhtmltopdf.org/

David Wall have and example with vaadin?

Well, there’s nothing Vaadin about wkhtmltopdf integration, just standard stuff related to any webapp. Of course, you’ll need to install a working copy of wkhtmltopdf and have it available in your PATH where ‘tomcat’ (or your web server) runs so that when you execute it, it can be found (or you can probably use a full path name to the executable as long as you have permissions).

We have code in our Open eSignForms platform that you can reference in source file com.esignforms.open.integration.wkhtmltopdf.HtmlToPdf (code is below, but it has hooks into our platform and such that you’ll probably need to tweak for your needs, and we digitally sign them as an option that may not be important to you as that requires PDFBox and BouncyCastle JARs):

// Copyright (C) 2011-2014 Yozons, Inc.
// Open eSignForms - Web-based electronic contracting software
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License
// as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this program.  
// If not, see [| html.length == 0 )
            return null;
        
        BufferedReader commandReader = null;
        String commandOutput = null;
        BufferedInputStream pdfIs = null;
        File workDir = null;
        File pdfFile = null;
        File signedPdfFile = null; // optional; exists only if digitally signed
        
        try
        {
            workDir = getWorkDirectory();
            if ( workDir == null )
                return null;
            
            pdfFile = createPdfFile(workDir);
            if ( digitallySign )
            {
                signedPdfFile = createSignedPdfFile(workDir);
                if ( _debugKeepGeneratedFiles )
                    signatureFile = createSignatureFile(workDir);
            }
            
            LinkedList<String](http://open.esignforms.com/agpl.txt> or http://www.gnu.org/licenses/.
// Contact information is via the public forums at http://open.esignforms.com or via private email to open-esign@yozons.com.
//

package com.esignforms.open.integration.wkhtmltopdf;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Calendar;
import java.util.LinkedList;

import org.apache.pdfbox.exceptions.SignatureException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;

import com.esignforms.open.Application;
import com.esignforms.open.admin.SignatureKey;
import com.esignforms.open.crypto.PublicKeyGenerator;
import com.esignforms.open.data.EsfString;

/**
 * Handles integration with wkhtmltopdf via Java ProcessBuilder to "print" one or more HTML
 * files (as Strings) into a PDF that is returned as a byte array.
 * wkhtmltopdf is an open source (LGPL) project at: http://code.google.com/p/wkhtmltopdf/
 *
 * @author Yozons, Inc.
 *
 */
public class HtmlToPdf
    implements SignatureInterface
{
    private static com.esignforms.open.log.Logger _logger = new com.esignforms.open.log.Logger(HtmlToPdf.class);

    private int htmlFileNum = 0;
    
    final boolean _debugKeepGeneratedFiles = false; // set to true when debugging so that the various generated files are kept
    File signatureFile = null; // when non-null, we'll write out the generated signature into its own file
        
    public HtmlToPdf()
    {
    }
    
    /**
     * Generates a PDF containing the list of HTML "files" (as Strings). The PDF will have the
     * HTML files in the order presented.
     * @param html a list of one or more Strings each containing the HTML to convert to PDF.
     * @return the byte array that represents the PDF file, or null if there's an error.
     */
    public byte[] generateLandscapePdf(String... html)
    {
        return generatePdf(true,false,html);
    }
    public byte[] generateLandscapeSignedPdf(String... html)
    {
        return generatePdf(true,true,html);
    }

    public byte[] generatePdf(String... html)
    {
        return generatePdf(false,false,html);
    }
    public byte[] generateSignedPdf(String... html)
    {
        return generatePdf(false,true,html);
    }
    
    public byte[] generatePdf(boolean inLandscape, boolean digitallySign, String... html)
    {
        if ( html == null ) command = new LinkedList<String>();
            if (System.getProperty("os.name").contains("Windows"))
                command.add("wkhtmltopdf.exe"); // the command should be in our Windows PATH
            else
                command.add("wkhtmltopdf"); // the command should be in our Linux PATH. (Renamed from wkhtmltopdf-i386 as of version 12.9.29 to get rid of non-required architecture specification.)
            if ( html.length > 1 ) // 11/24/2014 "hack" for multi-file PDFs to avoid an wkhtmltopdf 0.12.1 warning that causes fonts and checkbox/radio button images to sometimes fail
            {
                command.add("--javascript-delay");
                    command.add("1000");
            }
            if ( inLandscape )
            {
                command.add("--orientation");
                    command.add("Landscape");
            }
            command.add("--page-size");
                command.add("Letter");
            command.add("--encoding"); // shouldn't be necessary since our HTML files are encoded correctly
                command.add("utf-8");
            command.add("--print-media-type");
            // command.add("--disable-external-links"); Removed 8/31/2014 when FileConfirmLink and FileUpload fields were made into reusable URLs
            command.add("--image-quality");
                command.add("100");
            command.add("--margin-left");
                command.add("5mm");
            command.add("--margin-right");
                command.add("5mm");
            command.add("--margin-top");
                command.add("5mm");
            command.add("--margin-bottom");
                command.add("5mm");
            for( String h : html )
                command.add( createHtmlFile(workDir,h).getAbsolutePath() );
            command.add(pdfFile.getAbsolutePath());
            
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.directory( workDir );
            pb.redirectErrorStream(true);
            
            Process p = pb.start();
            
            p.getOutputStream().close(); // we have no input to give it
            
            StringBuilder outputBuf = new StringBuilder(1024);
            
            commandReader = new java.io.BufferedReader( new java.io.InputStreamReader(p.getInputStream()));
            String str;
            while ( (str = commandReader.readLine()) != null )
            {
                if ( EsfString.isBlank(str) )
                    continue;
                outputBuf.append(str).append('\n');
            }
            commandReader.close(); commandReader = null;

            commandOutput = outputBuf.toString();
            
            int exitCode = p.waitFor();
            
            if ( exitCode == 0 )
            {
                if ( commandOutput.contains("Error: ") || commandOutput.contains("Warning: ") )
                    _logger.warn("generatePdf() - Successful run shows error/warning in commandOutput: " + commandOutput);
                
                if ( digitallySign )
                {
                    if ( signPdf(pdfFile, signedPdfFile) )
                    {
                        pdfIs = new java.io.BufferedInputStream( new java.io.FileInputStream(signedPdfFile) );
                        
                        int fileSize = (int)signedPdfFile.length();                
                        byte[] pdfData = new byte[fileSize]
;
                        
                        int pdfDataOffset = 0;
                        int numRead;
                        int bytesToRead = fileSize;
                        while( bytesToRead > 0 && (numRead = pdfIs.read(pdfData,pdfDataOffset,bytesToRead)) > 0 )
                        {
                            pdfDataOffset += numRead;
                            bytesToRead -= numRead;
                        }

                        pdfIs.close(); pdfIs = null;
                        
                        return pdfData;
                    }
                    
                    _logger.error("generatePdf() - failed to digitally sign PDF so returning unsigned one instead.");
                    // we're going to fall through and return the unsigned PDF since not sure what has gone wrong
                }

                pdfIs = new java.io.BufferedInputStream( new java.io.FileInputStream(pdfFile) );
                
                int fileSize = (int)pdfFile.length();                
                byte[] pdfData = new byte[fileSize]
;
                
                int pdfDataOffset = 0;
                int numRead;
                int bytesToRead = fileSize;
                while( bytesToRead > 0 && (numRead = pdfIs.read(pdfData,pdfDataOffset,bytesToRead)) > 0 )
                {
                    pdfDataOffset += numRead;
                    bytesToRead -= numRead;
                }

                pdfIs.close(); pdfIs = null;
                    
                return pdfData;
            }

            _logger.error("generatePdf() - failed with exit status: " + exitCode);
            _logger.error("generatePdf() - commandOutput: " + commandOutput);
            return null;
        }
        catch( Exception e )
        {
            _logger.error("generatePdf() - commandOutput: " + commandOutput, e);
            return null;
        }
        finally
        {
            if ( commandReader != null )
            {
                try { commandReader.close(); } catch(Exception e){}
            }
            
            if ( pdfIs != null )
            {
                try { pdfIs.close(); } catch(Exception e){}
            }
            
            if ( workDir != null )
                cleanup(workDir);
        }
    }
    
    
    File createHtmlFile(File workDir, String html)
    {
        // TODO: 11/25/2014 - Found wkhtmltopdf 0.12.1 does not handle border-radius well (very slow) so we strip them out here.
        // Once this is fixed in wkhtmltopdf, we can remove this code.
        html = html.replaceAll("border-radius: *[0-9.]
+(px|em|en);", "");
        
        File htmlFile = new File(workDir,"file" + (htmlFileNum++) + ".html");
        
        BufferedWriter bw = null;
        try
        {
            bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(htmlFile), EsfString.CHARSET_UTF_8 ) );
            bw.write(html);
            bw.close();
            bw = null;
        }
        catch( Exception e )
        {
            _logger.error("createHtmlFile() - html file: " + htmlFile.getAbsolutePath(), e);
        }
        finally
        {
            if ( bw != null )
            {
                try    { bw.close(); } catch( Exception e ) {}
            }
        }
        
        return htmlFile;
    }
    
    File createPdfFile(File workDir)
    {
        File pdfFile = new File(workDir,"generated.pdf");
        return pdfFile;
    }
    
    File createSignedPdfFile(File workDir)
    {
        File pdfFile = new File(workDir,"signed.pdf");
        return pdfFile;
    }
    
    // Used when debugging
    File createSignatureFile(File workDir)
    {
        File sigFile = new File(workDir,"signature.dat");
        return sigFile;
    }
    
    File getWorkDirectory()
    {
        Application app = Application.getInstance();
        
        File deploymentBasePath = new File(app.getMyDeploymentBasePath());
        if ( ! deploymentBasePath.exists() )
        {
            _logger.error("getWorkDirectory() - Failed to find deployment base path: " + app.getDeploymentBasePath());
            return null;
        }

        File wkhtmltopdfDir = new File(deploymentBasePath,"wkhtmltopdf");
        if ( ! wkhtmltopdfDir.exists() )
        {
            if ( ! wkhtmltopdfDir.mkdir() )
            {
                _logger.error("getWorkDirectory() - Failed to create wkhtmltopdf directory in the deployment base dir: " + deploymentBasePath.getAbsolutePath());
                return null;
            }
        }
        
        File workDir = new File(wkhtmltopdfDir,"work");
        if ( ! workDir.exists() )
        {
            if ( ! workDir.mkdir() )
            {
                _logger.error("getWorkDirectory() - Failed to create work directory in the wkhtmltopdf dir: " + wkhtmltopdfDir.getAbsolutePath());
                return null;
            }
        }
        
        String randomPath = app.getRandomKey().getPickupCodeString();
        File randomWorkDir = new File(workDir,randomPath);
        if ( ! randomWorkDir.exists() )
        {
            if ( ! randomWorkDir.mkdir() )
            {
                _logger.error("getWorkDirectory() - Failed to create random directory in the wkhtmltopdf work dir: " + workDir.getAbsolutePath());
                return null;
            }
        }
        
        return randomWorkDir;
    }
    
    void cleanup(File workDir)
    {
        // Don't remove the files if we're supposed to keep them
        if ( _debugKeepGeneratedFiles )
            return;
        
        for( File f : workDir.listFiles() )
        {
            f.delete();
        }
        workDir.delete();
    }

    // From the PDFBox Signing.java example source file, modified with new BouncyCastle examples from org.bouncycastle.cms.CMSSignedDataGenerator.
    // Currently works using a self-signed certificate based on our signature keys.
    
    boolean signPdf(File pdfFile, File signedPdfFile)
    {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        PDDocument doc = null;
        
        try
        {
            fis = new FileInputStream(pdfFile);
            fos = new FileOutputStream(signedPdfFile);
            
            int readCount;
            byte[] buffer = new byte[8 * 1024]
;
            while ((readCount = fis.read(buffer)) != -1)
            {
              fos.write(buffer, 0, readCount);
            }
            fis.close();
            fis = new FileInputStream(signedPdfFile);
            
            doc = PDDocument.load(pdfFile);
            PDSignature signature = new PDSignature();
            signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
            signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
            signature.setName("Open eSignForms Export PDF Integrity Lock");
            signature.setLocation(Application.getInstance().getExternalContextPath());
            signature.setReason("Used to ensure that an exported PDF has not been tampered with since its generation by Open eSignForms deployment id: " +
                     Application.getInstance().getDeployId());
            signature.setSignDate(Calendar.getInstance());
            doc.addSignature(signature, this);
            doc.saveIncremental(fis, fos);
            return true;
        }
        catch( Exception e )
        {
            _logger.error("signPdf() - Failed to sign the PDF",e);
            return false;
        }
        finally
        {
            if ( fis != null ) try { fis.close(); } catch( Exception e ) {}
            if ( fos != null ) try { fos.close(); } catch( Exception e ) {}
            if ( doc != null ) try { doc.close(); } catch( Exception e ) {}
        }
    }

    @Override
    public byte[] sign(InputStream is) throws SignatureException, IOException
    {
        Application app = Application.getInstance();
        try
        {
            String provider = app.getPublicKeyGenerator().getProvider();
            SignatureKey signatureKey = app.getSignatureKey();
            X509Certificate cert = signatureKey.getX509Certificate();
            Store certStore = new JcaCertStore(Arrays.asList(cert));

            CMSTypedDataInputStream input = new CMSTypedDataInputStream(is);
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            ContentSigner sha512Signer = new JcaContentSignerBuilder(PublicKeyGenerator.SIGNATURE_ALGORITHM).setProvider(provider).build(signatureKey.getPrivateKey());
            
            gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                    new JcaDigestCalculatorProviderBuilder().setProvider(provider).build()).build(sha512Signer, cert));
            gen.addCertificates(certStore);
            CMSSignedData signedData = gen.generate(input, false);

            byte[] signatureData = signedData.getEncoded();
            
            if ( signatureFile != null )
            {
                FileOutputStream fos = null;
                try
                {
                    fos = new FileOutputStream(signatureFile);
                    fos.write(signatureData);
                    fos.close(); fos = null;
                }
                catch( Exception e )
                {
                    _logger.error("signPdf() - Failed to write signature file",e);
                }
                finally
                {
                    if ( fos != null ) try { fos.close(); } catch( Exception e ) {}
                }
            }
            
            return signatureData;
        }
        catch (Exception e)
        {
            _logger.error("sign() - Problem while preparing PDF signature",e);
            return null;
        }
    }
    
    class CMSTypedDataInputStream implements CMSTypedData
    {

        InputStream in;

        public CMSTypedDataInputStream(InputStream is)
        {
            in = is;
        }

        @Override
        public ASN1ObjectIdentifier getContentType()
        {
            return PKCSObjectIdentifiers.data;
        }

        @Override
        public Object getContent()
        {
            return in;
        }

         @Override
         public void write(OutputStream out) throws IOException, CMSException
         {
             byte[] buffer = new byte[8 * 1024]
;
             int read;
             while( (read = in.read(buffer)) != -1 )
             {
                 out.write(buffer, 0, read);
            }
            in.close();
         }
    }

}

Thanks Marko Radinović the code worked halfway, the PDF print it, but when I want to open it always gives me error “pdf file is unreadable”

I am using ZetPDF SDK number of time. It is too easy to develop PDF functionality using this SDK. You can download the SDK from here. http//zetpdf.com/

Serge Floyd:
I am using ZetPDF SDK number of time. It is too easy to develop PDF functionality using this SDK. You can download the SDK from here. http//zetpdf.com/

bad url. this api, it´s not for java.