Example usage for com.itextpdf.text.pdf PdfWriter setInitialLeading

List of usage examples for com.itextpdf.text.pdf PdfWriter setInitialLeading

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter setInitialLeading.

Prototype

public void setInitialLeading(final float leading) throws DocumentException 

Source Link

Document

Sets the initial leading for the PDF document.

Usage

From source file:org.smap.sdal.managers.MiscPDFManager.java

License:Open Source License

public void createTasksPdf(Connection sd, OutputStream outputStream, String basePath,
        HttpServletRequest request, HttpServletResponse response, int tgId) {

    try {//  w  w  w.j a v  a 2  s.c om

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        /*
         * Get the tasks for this task group
         */
        String urlprefix = request.getScheme() + "://" + request.getServerName();
        TaskManager tm = new TaskManager(localisation, tz);
        TaskListGeoJson t = tm.getTasks(sd, urlprefix, 0, tgId, 0, false, 0, null, "all", 0, 0, "scheduled",
                "desc");
        PdfWriter writer = null;

        String filename = "tasks.pdf";
        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            setFilenameInResponse(filename, response);
        }

        Document document = new Document(PageSize.A4);
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
        writer = PdfWriter.getInstance(document, outputStream);

        writer.setInitialLeading(12);
        writer.setPageEvent(new PageSizer());
        document.open();

        PdfPTable table = new PdfPTable(4);

        // Add the header row
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("Form Name");
        table.addCell("Task Name");
        table.addCell("Status");
        table.addCell("Assigned To");

        table.setHeaderRows(1);

        // Add the task data

        table.getDefaultCell().setBackgroundColor(null);
        for (TaskFeature tf : t.features) {
            TaskProperties p = tf.properties;

            table.addCell(p.survey_name);
            table.addCell(p.name);
            table.addCell(p.status);
            table.addCell(p.assignee_name);

        }

        document.add(table);
        document.close();

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    }

}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

public String createPdf(OutputStream outputStream, String basePath, String serverRoot, String remoteUser,
        String language, boolean generateBlank, String filename, boolean landscape, // Set true if landscape
        HttpServletResponse response) throws Exception {

    if (language != null) {
        language = language.replace("'", "''"); // Escape apostrophes
    } else {// w  ww  . j  a v a2s  .  c  o m
        language = "none";
    }

    mExcludeEmpty = survey.exclude_empty;

    User user = null;

    ServerManager serverManager = new ServerManager();
    ServerData serverData = serverManager.getServer(sd, localisation);

    UserManager um = new UserManager(localisation);
    int[] repIndexes = new int[20]; // Assume repeats don't go deeper than 20 levels

    Document document = null;
    PdfWriter writer = null;
    PdfReader reader = null;
    PdfStamper stamper = null;

    try {

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            //FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/Library/Fonts/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Bold.ttf", "bengalibold");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Bold.ttf", "bengalibold");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFontLink = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("notosans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        defaultFontBold = FontFactory.getFont("notosansbold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        arabicFont = FontFactory.getFont("arabic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFont = FontFactory.getFont("bengali", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFontBold = FontFactory.getFont("bengalibold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        defaultFontLink.setColor(BaseColor.BLUE);

        /*
         * Get the results and details of the user that submitted the survey
         */

        log.info("User Ident who submitted the survey: " + survey.instance.user);
        String userName = survey.instance.user;
        if (userName == null) {
            userName = remoteUser;
        }
        if (userName != null) {
            user = um.getByIdent(sd, userName);
        }

        // If a filename was not specified then get one from the survey data
        // This filename is returned to the calling program so that it can be used as a permanent name for the temporary file created here
        // If the PDF is to be returned in an http response then the header is set now before writing to the output stream
        log.info("Filename passed to createPDF is: " + filename);
        if (filename == null) {
            filename = survey.getInstanceName() + ".pdf";
        } else {
            if (!filename.endsWith(".pdf")) {
                filename += ".pdf";
            }
        }

        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            GeneralUtilityMethods.setFilenameInResponse(filename, response);
        }

        /*
         * Get a template for the PDF report if it exists
         * The template name will be the same as the XLS form name but with an extension of pdf
         */
        File templateFile = GeneralUtilityMethods.getPdfTemplate(basePath, survey.displayName, survey.p_id);

        /*
         * Get dependencies between Display Items, for example if a question result should be added to another
         *  question's results
         */
        GlobalVariables gv = new GlobalVariables();
        if (!generateBlank) {
            for (int i = 0; i < survey.instance.results.size(); i++) {
                getDependencies(gv, survey.instance.results.get(i), survey, i);
            }
        }
        gv.mapbox_key = serverData.mapbox_default;
        int oId = GeneralUtilityMethods.getOrganisationId(sd, remoteUser);

        languageIdx = GeneralUtilityMethods.getLanguageIdx(survey, language);
        if (templateFile.exists()) {

            log.info("PDF Template Exists");
            String templateName = templateFile.getAbsolutePath();

            reader = new PdfReader(templateName);
            stamper = new PdfStamper(reader, outputStream);

            for (int i = 0; i < survey.instance.results.size(); i++) {
                fillTemplate(gv, stamper.getAcroFields(), survey.instance.results.get(i), basePath, null, i,
                        serverRoot, stamper, oId);
            }
            if (user != null) {
                fillTemplateUserDetails(stamper.getAcroFields(), user, basePath);
            }
            stamper.setFormFlattening(true);

        } else {
            log.info("++++No template exists creating a pdf file programmatically");

            /*
             * Create a PDF without the stationary
             * If we need to add a letter head then create document in two passes, the second pass adds the letter head
             * Else just create the document directly in a single pass
             */
            Parser parser = getXMLParser();

            // Step 1 - Create the underlying document as a byte array
            if (landscape) {
                document = new Document(PageSize.A4.rotate());
            } else {
                document = new Document(PageSize.A4);
            }
            document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
            writer = PdfWriter.getInstance(document, outputStream);

            writer.setInitialLeading(12);

            writer.setPageEvent(new PdfPageSizer(survey.displayName, survey.projectName, user, basePath, null,
                    marginLeft, marginRight, marginTop_2, marginBottom_2));
            document.open();

            // If this form has data maintain a list of parent records to lookup ${values}
            ArrayList<ArrayList<Result>> parentRecords = null;
            if (!generateBlank) {
                parentRecords = new ArrayList<ArrayList<Result>>();
            }

            for (int i = 0; i < survey.instance.results.size(); i++) {
                processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                        generateBlank, 0, i, repIndexes, gv, false, parentRecords, remoteUser, oId);
            }

            fillNonTemplateUserDetails(document, user, basePath);

            // Add appendix
            if (gv.hasAppendix) {
                document.newPage();
                document.add(new Paragraph("Appendix", defaultFontBold));

                for (int i = 0; i < survey.instance.results.size(); i++) {
                    processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                            generateBlank, 0, i, repIndexes, gv, true, parentRecords, remoteUser, oId);
                }
            }

        }

    } finally {
        if (document != null)
            try {
                document.close();
            } catch (Exception e) {
            }
        ;
        if (writer != null)
            try {
                writer.close();
            } catch (Exception e) {
            }
        ;
        if (stamper != null)
            try {
                stamper.close();
            } catch (Exception e) {
            }
        ;
        if (reader != null)
            try {
                reader.close();
            } catch (Exception e) {
            }
        ;
    }

    return filename;

}

From source file:org.smap.sdal.managers.PDFTableManager.java

License:Open Source License

public void createPdf(Connection sd, OutputStream outputStream, ArrayList<ArrayList<KeyValue>> dArray,
        SurveyViewDefn mfc, ResourceBundle localisation, String tz, boolean landscape, String remoteUser,
        String basePath, String title, String project) {

    User user = null;//from  w  w  w  .  j a v  a  2s .  c  o  m
    UserManager um = new UserManager(localisation);

    try {

        user = um.getByIdent(sd, remoteUser);

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        ArrayList<PdfColumn> cols = getPdfColumnList(mfc, dArray, localisation);
        ArrayList<String> tableHeader = new ArrayList<String>();
        for (PdfColumn col : cols) {
            tableHeader.add(col.displayName);
        }
        /*
         * Create a PDF without the stationary
         */
        PdfWriter writer = null;

        /*
         * If we need to add a letter head then create document in two passes, the second pass adds the letter head
         * Else just create the document directly in a single pass
         */
        Parser parser = getXMLParser();

        // Step 1 - Create the underlying document as a byte array
        Document document = null;
        if (landscape) {
            document = new Document(PageSize.A4.rotate());
        } else {
            document = new Document(PageSize.A4);
        }
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
        writer = PdfWriter.getInstance(document, outputStream);

        writer.setInitialLeading(12);
        writer.setPageEvent(new PdfPageSizer(title, project, user, basePath, tableHeader, marginLeft,
                marginRight, marginTop_2, marginBottom_2));

        document.open();
        document.add(new Chunk("")); // Ensure there is something in the page so at least a blank document will be created
        processResults(parser, document, dArray, cols, basePath);
        document.close();

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    }

}

From source file:projekt.Class.SaveToPDF.java

/**
 * * Metoda, ktra tworzy plik pdf na podan ciek
 *
 * @param file cieka dostpu do pluku na ktrym ma by zapisaby plik pdf
 * @throws IOException       wyjtek wejcia/ wyjcia
 * @throws DocumentException wyjatek podczas tworzenia dokumentu
 *//*from ww  w .  ja v  a 2s  . c  om*/
public static void createPdf(File file) throws IOException, DocumentException {
    Document document = new Document();
    String HTML = "src/projekt/HTML/Diagnoza/diagnoza.html";
    String CSS = "src/projekt/HTML/Diagnoza/styl.css";
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    writer.setInitialLeading(12.5f);
    document.open();
    CSSResolver cssResolver = new StyleAttrCSSResolver();
    CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream(CSS));
    cssResolver.addCss(cssFile);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    p.parse(new FileInputStream(HTML));
    document.close();
}

From source file:Ventas.GeneradorFormato.java

public static void main(String[] args) {
    try {//ww w  .  j  a v  a 2 s.co  m

        Document document = new Document(PageSize.LETTER, 50, 50, 85, 50);
        document.addAuthor("Ventas");
        document.addTitle("Ventas");

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        writer.setInitialLeading(16);
        Rectangle rct = new Rectangle(80, 104, 500, 688);
        writer.setBoxSize("art", rct);
        HeaderFooter event = new HeaderFooter();
        writer.setPageEvent(event);

        document.open();
        //            Paragraph parrafo2 = new Paragraph("De aqui en ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED));
        //            parrafo2.setAlignment(0);
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Fecha:"));
        Paragraph id_Venta = new Paragraph("ID_Venta:");
        id_Venta.setAlignment(0);
        document.add(id_Venta);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        //            document.add(parrafo2);
        document.add(new Paragraph("Nombre del cliente:"));
        //            document.add(Chunk.NEWLINE);
        //            document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Apellido Paterno:"));
        //            document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Apellido Materno:"));
        document.add(new Paragraph("Domicilio:"));
        document.add(new Paragraph("Calle:"));
        document.add(new Paragraph("Numero:"));
        document.add(new Paragraph(""));

        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.close();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}