Example usage for com.itextpdf.text Document open

List of usage examples for com.itextpdf.text Document open

Introduction

In this page you can find the example usage for com.itextpdf.text Document open.

Prototype

boolean open

To view the source code for com.itextpdf.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

From source file:com.primeleaf.krystal.web.action.console.OpenDocumentClassAction.java

License:Open Source License

private File generatePdfFile(ArrayList<Hit> hits, ArrayList<IndexDefinition> indexes, User loggedInUser)
        throws Exception {
    File tempPdf = File.createTempFile("tempPdf", ".pdf");
    FileOutputStream file = new FileOutputStream(tempPdf);
    Document document = new Document(PageSize.A3.rotate());
    PdfWriter.getInstance(document, file);
    document.open();

    Font boldFont12 = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Font normalFont10 = new Font(FontFamily.HELVETICA, 10, Font.NORMAL);

    int colCount = 9; //predefined columns count
    int colSize = indexes.size() + colCount;
    float[] columnWidths = new float[colSize];

    for (int i = 0; i < columnWidths.length; i++) {
        columnWidths[i] = (100 / colSize);
    }//from w  w  w  .ja  va  2 s .c o m

    PdfPTable table = new PdfPTable(columnWidths);
    table.setWidthPercentage(100f);

    if (hits.size() > 0) {
        BaseColor bgColor = new BaseColor(225, 240, 255);

        insertCellPDF(table, "Document ID", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "Revision ID", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "Created By", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "Last Modified By", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "File Size", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "Created On", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "Last Modified On", Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        insertCellPDF(table, "Expiry On", Element.ALIGN_CENTER, 1, boldFont12, bgColor);

        for (IndexDefinition index : indexes) {
            insertCellPDF(table, index.getIndexDisplayName(), Element.ALIGN_CENTER, 1, boldFont12, bgColor);
        }

        insertCellPDF(table, "Note", Element.ALIGN_CENTER, 1, boldFont12, bgColor);

        int count = 0;

        for (Hit hit : hits) {
            count++;
            if (count % 2 == 0) {
                bgColor = new BaseColor(240, 240, 240);
            } else {
                bgColor = new BaseColor(210, 210, 210);
            }
            insertCellPDF(table, hit.documentId + "", Element.ALIGN_CENTER, 1, normalFont10, bgColor);
            insertCellPDF(table, hit.revisionId, Element.ALIGN_CENTER, 1, normalFont10, bgColor);
            insertCellPDF(table, hit.createdBy, Element.ALIGN_CENTER, 1, normalFont10, bgColor);
            insertCellPDF(table, hit.modifiedBy + "", Element.ALIGN_CENTER, 1, normalFont10, bgColor);
            insertCellPDF(table, StringHelper.formatSizeText(hit.fileLength), Element.ALIGN_CENTER, 1,
                    normalFont10, bgColor);
            insertCellPDF(table, hit.created, Element.ALIGN_CENTER, 1, normalFont10, bgColor);
            insertCellPDF(table, hit.modified, Element.ALIGN_CENTER, 1, normalFont10, bgColor);
            insertCellPDF(table, hit.expiryOn, Element.ALIGN_CENTER, 1, normalFont10, bgColor);

            for (String index : hit.indexValues) {
                insertCellPDF(table, index, Element.ALIGN_LEFT, 1, normalFont10, bgColor);
            }

            ArrayList<DocumentNote> documentNotes = DocumentNoteDAO.getInstance()
                    .readJournalNotes("DOCUMENTID=" + hit.documentId + " AND ACTIVE ='Y' ORDER BY 1 DESC");
            String notesData = "";
            if (documentNotes.size() > 0) {
                for (DocumentNote documentNote : documentNotes) {
                    if (!"P".equalsIgnoreCase(documentNote.getNoteType())) {
                        if (!loggedInUser.getUserName().equalsIgnoreCase(documentNote.getUserName())) {
                            continue;
                        }
                    }
                    User user = UserDAO.getInstance().readUserByName(documentNote.getUserName());
                    notesData += documentNote.getNoteData() + "\n";
                    notesData += "Posted By" + " : " + user.getRealName() + "\n";
                    notesData += "Posted On" + " : " + StringHelper.formatDate(documentNote.getCreated());
                    notesData += "\n";
                }
            }
            insertCellPDF(table, notesData, Element.ALIGN_LEFT, 1, normalFont10, bgColor);
        }
    }
    try {
        document.add(table);
        document.close();
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return tempPdf;
}

From source file:com.prjhuellvotweb.controlador.PDF.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Preguntar por la sesion del usuario admin
    HttpSession sessionOk = request.getSession(true);
    if (sessionOk.getAttribute("admin") != null) {
        //cambiar a tipo application/pdf
        response.setContentType("application/pdf;charset=UTF-8");
        //flujo de salida
        OutputStream out = response.getOutputStream();
        String texto = request.getParameter("report");
        //texto = "Reporte de los proyectos Sena CTGI (Centro tecnologico de gestion industrial) donde se dan a conocer"
        //                   + " los nombres de los proyectos y cantidad de votos obtenidos para cada proyecto.";
        try {/* w  w w  .ja  va2  s  .c  o  m*/
            Connection con = Conexion.conectar("mysql");
            DAOVoto dao = new DAOVoto();
            List<List> lista = dao.estadisticaNumeroVotos();
            Voto t = dao.contarVotos();
            int to = t.getIdUsuario();
            if (!lista.isEmpty() && lista.size() > 0) {
                try {
                    //programar pdf
                    Document documento = new Document();
                    //asosciar documento con la salida
                    PdfWriter.getInstance(documento, out);// salida del cocumento en pdf
                    //abrir documento
                    documento.open();
                    Paragraph par2 = new Paragraph();
                    Paragraph par4 = new Paragraph();
                    //agregar una imagen logo sena al pdf
                    Image imagenes = Image
                            .getInstance(getServletContext().getRealPath("") + "/Multimedia/reportes.png");
                    //Centrar la imagen
                    imagenes.setAlignment(Element.ALIGN_CENTER);
                    //tamao de la imagen
                    imagenes.scaleToFit(530, 520);
                    //agg imagen al documento F:\\Documentos\\yo\\huellvot 2 17-06-2016\\PrjHuellVotWeb\\web\\iCO.png
                    //documento.add(imghuellvot);
                    documento.add(imagenes);
                    //Agg salto de linea
                    par2.add(new Phrase(Chunk.NEWLINE));
                    par2.add(new Phrase(Chunk.NEWLINE));

                    //fuente del pdf, tipo de fuente famimilia tamao de letra
                    //Importar ttf que contiene el tipo de letra
                    FontFactory.register(
                            "C:\\Users\\pc\\Desktop\\PrjHuellVotWeb\\web\\fonts\\roboto\\Roboto-Bold.ttf",
                            "Roboto");
                    //Font fondescripcion = FontFactory.getFont("Roboto");
                    Font fondescripcion = new Font(Font.getFamily("Roboto"), 16, Font.NORMAL, BaseColor.BLACK);
                    //texto de la descripcion
                    par2.add(new Phrase(texto, fondescripcion));
                    //justificar descripcion
                    par2.setAlignment(Element.ALIGN_JUSTIFIED);
                    //Agg salto de linea
                    par2.add(new Phrase(Chunk.NEWLINE));
                    par2.add(new Phrase(Chunk.NEWLINE));
                    //agregar descripcion al documento
                    documento.add(par2);//agregar todas las propiedades de la descripcin
                    //crear una tabla
                    PdfPTable tabla = new PdfPTable(5);//( Numero de columnas de la tabla)
                    //columnas de la tabla, cabezera y agg un estilo
                    PdfPCell celda = new PdfPCell(
                            new Paragraph("Nmero", FontFactory.getFont("Roboto", 14, Font.BOLD)));
                    PdfPCell celda1 = new PdfPCell(
                            new Paragraph("Nombre", FontFactory.getFont("Roboto", 14, Font.BOLD)));
                    celda1.setColspan(3);
                    PdfPCell celda2 = new PdfPCell(
                            new Paragraph("Votos", FontFactory.getFont("Roboto", 14, Font.BOLD)));
                    //Color de fondo
                    celda.setBackgroundColor(new BaseColor(252, 115, 35));
                    celda1.setBackgroundColor(new BaseColor(252, 115, 35));
                    celda2.setBackgroundColor(new BaseColor(252, 115, 35));
                    //Centrar
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    //padding
                    celda.setPadding(8.0f);
                    celda1.setPadding(8.0f);
                    celda2.setPadding(8.0f);
                    //agg columna ala tabla
                    tabla.addCell(celda);
                    tabla.addCell(celda1);
                    tabla.addCell(celda2);

                    for (int i = 0; i < lista.size(); i++) {
                        List l = lista.get(i);
                        //Convertir el entero a string
                        String num = String.valueOf(l.get(0));
                        String nom = String.valueOf(l.get(1));
                        String tot = String.valueOf(l.get(2));
                        //Agregar valores a las celdas
                        PdfPCell c = new PdfPCell(
                                new Paragraph(num, FontFactory.getFont("Roboto", 12, Font.BOLD)));
                        PdfPCell c1 = new PdfPCell(
                                new Paragraph(nom, FontFactory.getFont("Roboto", 12, Font.BOLD)));
                        c1.setColspan(3);
                        PdfPCell c2 = new PdfPCell(
                                new Paragraph(tot, FontFactory.getFont("Roboto", 12, Font.BOLD)));
                        //Padding para las celdas
                        c.setPadding(4.0f);
                        c1.setPadding(4.0f);
                        c2.setPadding(4.0f);
                        //Centrar contenido de celda
                        c.setHorizontalAlignment(Element.ALIGN_CENTER);
                        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
                        //mostrar los resultados de cada columna los agrega a la tabla
                        tabla.addCell(c);
                        tabla.addCell(c1);
                        tabla.addCell(c2);

                    }
                    PdfPCell c1 = new PdfPCell(new Paragraph("Total Votos: ", fondescripcion));
                    c1.setColspan(4);
                    PdfPCell c2 = new PdfPCell(new Paragraph("" + to, fondescripcion));

                    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    c2.setHorizontalAlignment(Element.ALIGN_CENTER);

                    c1.setPadding(4.0f);
                    c2.setPadding(4.0f);

                    tabla.addCell(c1);
                    tabla.addCell(c2);

                    //Agrega la tabla a el documento
                    documento.add(tabla);
                    //agregar fecha
                    Font fonfecha = new Font(Font.getFamily("Roboto"), 12, Font.NORMAL, BaseColor.LIGHT_GRAY);

                    par4.add(new Phrase("Expedido por HuellVot", fonfecha));
                    DateFormat formato = DateFormat.getDateInstance(DateFormat.FULL);
                    par4.add(new Paragraph(formato.format(new Date())));

                    documento.add(par4);

                    //cerrar el documento
                    documento.close();
                } catch (DocumentException | IOException e) {
                    e.getMessage();
                    System.out.println("Error al generar el reporte PDF" + e);
                }

            } else {
                try {
                    Document documento = new Document();
                    PdfWriter.getInstance(documento, out);// salida del cocumento en pdf
                    //abrir documento
                    documento.open();
                    System.out.println("no hat datos");
                    //agregar una imagen logo sena al pdf
                    Image imagenes = Image.getInstance(
                            "C:\\Users\\pc\\Desktop\\PrjHuellVotWeb\\web\\Multimedia\\reportes.png");
                    //Centrar la imagen
                    imagenes.setAlignment(Element.ALIGN_CENTER);
                    //tamao de la imagen
                    imagenes.scaleToFit(530, 520);
                    //agg imagen al documento F:\\Documentos\\yo\\huellvot 2 17-06-2016\\PrjHuellVotWeb\\web\\iCO.png
                    //documento.add(imghuellvot);
                    documento.add(imagenes);
                    Paragraph par1 = new Paragraph();
                    Paragraph par2 = new Paragraph();
                    //Agg salto de linea
                    par1.add(new Phrase(Chunk.NEWLINE));
                    par1.add(new Phrase(Chunk.NEWLINE));

                    //fuente del pdf, tipo de fuente famimilia tamao de letra
                    //Importar ttf que contiene el tipo de letra
                    FontFactory.register(
                            "C:\\Users\\pc\\Desktop\\PrjHuellVotWeb\\web\\fonts\\roboto\\Roboto-Bold.ttf",
                            "Roboto");
                    //Font fondescripcion = FontFactory.getFont("Roboto");
                    Font fondescripcion = new Font(Font.getFamily("Roboto"), 16, Font.NORMAL, BaseColor.BLACK);
                    //texto de la descripcion
                    par1.add(new Phrase("lo sentimos pero no hay datos para mostrar.!", fondescripcion));
                    //justificar descripcion
                    par1.setAlignment(Element.ALIGN_CENTER);
                    //Agg salto de linea
                    par1.add(new Phrase(Chunk.NEWLINE));
                    par1.add(new Phrase(Chunk.NEWLINE));
                    //agregar descripcion al documento
                    documento.add(par1);//agregar todas las propiedades de la descripcin
                    //agregar fecha
                    Font fonfecha = new Font(Font.getFamily("Roboto"), 12, Font.NORMAL, BaseColor.LIGHT_GRAY);

                    par2.add(new Phrase("Expedido por HuellVot", fonfecha));
                    DateFormat formato = DateFormat.getDateInstance(DateFormat.FULL);
                    par2.add(new Paragraph(formato.format(new Date())));
                    documento.add(par2);
                    //cerrar el documento
                    documento.close();
                } catch (DocumentException ex) {
                    ex.getMessage();
                    System.out.println("Error al generar el reporte PDF sin datos registrados" + ex);
                }

            }

        } finally {
            out.close();
        }
    } else {
        sessionOk.invalidate();
        response.sendRedirect("index.jsp");
    }
}

From source file:com.propelics.pdfcreator.PdfcreatorModule.java

License:Open Source License

/**
 * @method generatePDFWithHTML//ww  w . ja  v a2s.  c  o  m
 * Generates a PDF with the given file name, based on a HTML file
 * @param {String} filename Name of the PDF file
 * @param {String} html String with the HTML
 * @param {String} [author] Author for metadata
 * Fires a "complete" event when the PDF is generated
 * Fires a "error" event when a error is presented
 */
@Kroll.method(runOnUiThread = true)
public void generatePDFWithHTML(final HashMap args) {
    Log.d(PROXY_NAME, "generatePDFWithHTML()");

    String html = "";
    String author = "";
    String filename = "";
    final float marginPt = 28.35f;//1cm == 28.35pt

    try {
        if (args.containsKey("filename")) {
            filename = (String) args.get("filename");
            Log.d(PROXY_NAME, "filename: " + filename);
        } else
            return;

        if (args.containsKey("html")) {
            html = (String) args.get("html");
            Log.d(PROXY_NAME, "html: " + html);
        } else
            return;

        if (args.containsKey("author")) {
            author = (String) args.get("author");
            Log.d(PROXY_NAME, "author: " + author);
        }

        //create a new document
        Document document = new Document(PageSize.LETTER, marginPt, marginPt, marginPt, 0);
        TiBaseFile file = TiFileFactory.createTitaniumFile(filename, true);

        // Parse to XHTML
        StringWriter xhtmlWriter = new StringWriter();
        Tidy tidy = new Tidy();

        // tidy.setXHTML(true);
        tidy.setXmlOut(true);
        tidy.parse(new StringReader(html), xhtmlWriter);
        String xhtml = xhtmlWriter.toString();

        //get Instance of the PDFWriter
        PdfWriter pdfWriter = PdfWriter.getInstance(document, file.getOutputStream());

        //document header attributes
        document.addAuthor(author);
        document.addCreationDate();
        document.setPageSize(PageSize.LETTER);

        //open document
        document.open();

        // From Stack Overflow lol

        MyFontFactory fontFactory = new MyFontFactory();
        FontFactory.setFontImp(fontFactory);

        // HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(fontFactory));
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
        Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, pdfWriter)));
        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser p = new XMLParser(worker);
        p.parse(new StringReader(xhtml));

        // Finish SO c&P

        // Older code
        /*
        // Font Provider creation
        MyFontFactory fontProvider = new MyFontFactory();
        // fontProvider.register("/DroidSans.ttf");
                
        //get the XMLWorkerHelper Instance
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        //convert to PDF
        worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(xhtml.getBytes("UTF-8")), null, fontProvider); //Load xhtml
        */

        //close the document
        document.close();
        //close the writer
        pdfWriter.close();

        sendCompleteEvent(filename);

    } catch (Exception e) {
        sendErrorEvent(e);
    }
}

From source file:com.propelics.pdfcreator.PdfcreatorModule.java

License:Open Source License

private void generateiTextPDFfunction(HashMap args) {
    Log.d(PROXY_NAME, "generateiTextPDFfunction()");

    String filename = "";
    TiUIView webview = null;/*from  ww  w  .  j  a  va2 s. c  o m*/
    int quality = 100;

    try {
        if (args.containsKey("filename")) {
            filename = (String) args.get("filename");
            Log.d(PROXY_NAME, "filename: " + filename);
        } else
            return;

        if (args.containsKey("webview")) {
            TiViewProxy viewProxy = (TiViewProxy) args.get("webview");
            webview = viewProxy.getOrCreateView();
            Log.d(PROXY_NAME, "webview: " + webview.toString());
        } else
            return;

        if (args.containsKey("quality")) {
            quality = TiConvert.toInt(args.get("quality"));
        }

        TiBaseFile file = TiFileFactory.createTitaniumFile(filename, true);
        Log.d(PROXY_NAME, "file full path: " + file.nativePath());

        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = PageSize.LETTER.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = PageSize.LETTER.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(PageSize.LETTER, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.d(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.d(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) webview.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.d(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.d(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / (viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / (viewHeight / PDF_HEIGHT);

        Log.d(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.d(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile(filename);

        viewBitmap.compress(Bitmap.CompressFormat.PNG, quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.d(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent(filename);

    } catch (Exception exception) {
        sendErrorEvent(exception);
    }
}

From source file:com.quix.aia.cn.imo.mapper.ApplicationFormPDFMaintenance.java

License:Open Source License

public static InterviewCandidateMaterial pdf(HttpServletRequest request, AddressBook addressbook) {
    // TODO Auto-generated method stub
    log.log(Level.INFO, "ApplicationFormPDFMaintenance --> pdf ");
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    //Font myAdobeTypekit = FontFactory.getFont(request.getRealPath(File.separator)+"resources"+File.separator+"HDZB_35.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

    try {//from   ww w  .  j  a  va  2s.  c  om
        //String fontPath = "C:/Windows/Fonts";

        String fontPath = request.getRealPath("/") + "resources" + File.separator + "hxb-meixinti";
        File f2 = new File(fontPath + "/hxb-meixinti.ttf");
        BaseFont bf1 = null;
        if (f2.exists()) {
            bf1 = BaseFont.createFont(fontPath + "/hxb-meixinti.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } else {
            f2 = new File(fontPath + "/hxb-meixinti.ttf");

            if (f2.exists()) {
                System.out.println("File existed");
                bf1 = BaseFont.createFont(fontPath + "hxb-meixinti.ttf", BaseFont.IDENTITY_V,
                        BaseFont.EMBEDDED);
            } else {
                bf1 = BaseFont.createFont(FontManager.getFontPath(true) + "/hxb-meixinti.ttf",
                        BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }
        }

        Font normalFontCH = new Font(bf1, 15);

        String fileName = request.getRealPath("/") + "resources" + File.separator + "upload" + File.separator;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date();
        String time = (d1.getTime() + "").trim();
        String str = df.format(new Date()) + time;

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(fileName + "ApplicationForm_" + str + ".pdf"));
        InterviewCandidateMaterial material = new InterviewCandidateMaterial();
        material.setMaterialFileName("ApplicationForm_" + str + ".pdf");
        material.setCandidateCode(Integer.parseInt(request.getParameter("candidateCode")));
        material.setInterviewCode(Integer.parseInt(request.getParameter("interviewCode")));

        // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://applicatonForm2.pdf"));
        document.open();

        addTitle(document, writer, "formHeaderTitle", "Application Form");
        document = personalInformation(document, writer, addressbook, normalFontCH);
        document = familyInformation(document, writer, addressbook);
        document = workExperience(document, writer, addressbook);
        document = Education(document, writer, addressbook);
        document = personalCertification(document, writer, addressbook);
        document = ESingnature(document, writer, addressbook);

        document.close();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        File file = new File(fileName + "ApplicationForm_" + str + ".pdf");
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[1024];
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); //no doubt here is 0
        }
        material.setFormContent(bos.toByteArray());
        material.setCreatedDate(new Date());
        material.setMaterialDescrption("AppicationForm");

        //  applicationForm.setFormContent(bos.toByteArray());

        return material;
    } catch (Exception e) {
        log.log(Level.INFO, "ApplicationFormPDFMaintenance --> pdf --> Exception  " + e.getMessage());
        e.printStackTrace();
        e.printStackTrace();
        LogsMaintenance logsMain = new LogsMaintenance();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logsMain.insertLogs("ApplicationFormPDFMaintenance", Level.SEVERE + "", errors.toString());
    }

    return null;

}

From source file:com.raghav.plot.ImageIntoPDF.java

public static void main(String[] args) throws Exception {
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/raghav/zzzzz.pdf"));
    document.open();
    document.newPage();//from w w  w.ja  v  a 2s  . c o m

    //for 4 photo
    //        for (int i=0;i<2;i++) {
    //            Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png");
    //            image1.setAbsolutePosition(40,80+(350*i));
    //          image1.scaleAbsolute(200, 260);
    //            document.add(image1);
    //        }
    //          for (int i=0;i<2;i++) {
    //            Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png");
    //            image1.setAbsolutePosition(300, 80+(350*i));
    //          image1.scaleAbsolute(260, 200);
    //            document.add(image1);
    //        }
    //for 6

    float margin = 10;

    float docHeight = ((document.getPageSize().getHeight()) / 3) - (2 * margin);
    float docwidth = ((document.getPageSize().getWidth()) / 2) - (2 * margin);

    for (int i = 0; i < 3; i++) {
        Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg");

        image1.setAbsolutePosition(margin, margin * (i + 1) + (docHeight * i));
        image1.scaleToFit(docwidth, docHeight);
        //image1.scaleAbsolute(190, 130);
        document.add(image1);
    }
    for (int i = 0; i < 3; i++) {
        Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg");
        image1.setAbsolutePosition(docwidth + (2 * margin), margin * (i + 1) + (docHeight * i));
        image1.scaleToFit(docwidth, docHeight);
        document.add(image1);
    }
    document.close();
}

From source file:com.rapidminer.gui.actions.ExportPdfAction.java

License:Open Source License

/**
 * Create the PDF from a {@link Component}.
 * //  w ww  .j av a2  s. c o  m
 * @param component
 */
private void createPdf(Component component) {
    if (component == null) {
        return;
    }

    // prompt user for pdf location
    File file = promptForPdfLocation();
    if (file == null) {
        return;
    }

    try {
        // create pdf document
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        createPdfViaTemplate(component, document, cb);
        document.close();
    } catch (Exception e) {
        SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage());
    }
}

From source file:com.rapidminer.gui.actions.ExportPdfAction.java

License:Open Source License

/**
 * Create the PDF from a {@link PlotterTemplate}.
 * /*from   ww  w  .j ava 2  s.  c o m*/
 * @param template
 */
private void createPdf(PlotterTemplate template) {
    if (template == null) {
        return;
    }

    // prompt user for pdf location
    File file = promptForPdfLocation();
    if (file == null) {
        return;
    }

    try {
        // create pdf document
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        createPdfViaTemplate(template, document, cb);
        document.close();
    } catch (Exception e) {
        SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage());
    }
}

From source file:com.sample.biblio.fe.core.controller.ReportBean.java

@PostConstruct
public void init() {
    try {/*  ww  w .j a va 2 s . co m*/
        //----------------------------------
        Document doc = new Document();

        OutputStream out = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(doc, out);

        doc.open();
        doc.add(new Paragraph("Hello World. ok........"));
        doc.close();
        out.close();

        InputStream in = new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());

        streamedContent = new DefaultStreamedContent(in, "application/pdf");
        //-------
        Map<String, Object> session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        byte[] b = (byte[]) session.get("reportBytes");
        if (b != null) {
            streamedContent = new DefaultStreamedContent(new ByteArrayInputStream(b), "application/pdf");
        }
    } catch (Exception e) {
    }

}

From source file:com.sapito.direccion.PdfView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    ByteArrayOutputStream baos = createTemporaryOutputStream();
    Document document = new Document(PageSize.LETTER);
    PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
    pdfWriter.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage);

    document.open();
    buildPdfDocument(model, document, pdfWriter, request, response);
    document.close();//w w  w .jav a 2  s  .c o  m

    response.setHeader("Content-Disposition",
            "attachment; filename=" + model.get("filename").toString() + ".pdf");
    //response.setContentLength(baos.size());
    System.out.println("size:" + baos.size());
    writeToResponse(response, baos);

}