Example usage for com.lowagie.text Document open

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

Introduction

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

Prototype

boolean open

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

Click Source Link

Document

Is the document open or not?

Usage

From source file:com.moss.check.us.CheckPdfRenderer.java

License:Open Source License

public void render(CheckModel model, OutputStream out) throws Exception {

    Document document = new Document();
    document.setPageSize(new Rectangle(PAGE_WIDTH, PAGE_HEIGHT));

    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();

    PdfContentByte cb = writer.getDirectContent();

    Check check = new Check();
    check.defaultFont = BaseFont.createFont("Helvetica", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.defaultFontSize = 8;/*from www. ja v  a 2 s . c  o  m*/
    check.defaultFontLeading = 10;
    check.largeFontSize = 9;
    check.largeFontLeading = 12;
    check.fixedWidthFont = createFixedFont();
    check.fixedWidthFontSize = 8;
    check.voidFont = BaseFont.createFont("Helvetica-Bold", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.voidFontSize = 14;
    check.micrFont = createMicrFont();
    check.micrFontSize = 12;
    check.model = model;
    check.x = 0;
    check.y = 0;
    check.renderMode = CheckRenderMode.CHECK;

    check.render(cb);

    if (StubPrintMode.CHECK_DUPLICATE == model.stubPrintMode) {
        check.renderMode = CheckRenderMode.STUB;
        check.y = document.top() - (8.2f * POINTS_IN_A_CM);
        check.render(cb);
    } else if (StubPrintMode.CUSTOM == model.stubPrintMode) {
        PdfReader reader = new PdfReader(model.customStubPdf);
        PdfImportedPage customPage = writer.getImportedPage(reader, 1);
        cb.addTemplate(customPage, 0f, 0f);
    } else {
        throw new RuntimeException("Unknown stub print mode: " + model.stubPrintMode);
    }

    document.close();
}

From source file:com.moss.pdf.template.core.Renderer.java

License:Open Source License

public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception {

    PdfReader reader = new PdfReader(in);

    Document document = new Document(reader.getPageSizeWithRotation(1));

    PdfWriter writer = PdfWriter.getInstance(document, out);

    document.open();

    for (int i = 1; i <= reader.getNumberOfPages(); i++) {

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage customPage = writer.getImportedPage(reader, i);

        /*//  w  w  w  .  j  a v  a  2 s  .  c om
         * add the page to our new document, turning this page to its 
         * original rotation
         */
        int pageRotation = reader.getPageRotation(i);

        if (pageRotation > 0) {

            System.out.println("page rotation found: " + pageRotation);

            double angle = -((2 * Math.PI) * pageRotation / 360);
            //         double angle = -(Math.PI / 2);

            cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle),
                    (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x
                    document.top() + document.topMargin() // y
            );
        } else {
            cb.addTemplate(customPage, 0f, 0f);
        }

        Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>();

        for (PropertyMapping field : fields) {

            if (field.getPageNumber() != i) {
                continue;
            }

            /*
             * Only builtin fonts are supported at the moment
             */
            BaseFont font;
            int fontSize;
            int alignment;
            String text;
            float x, y;
            float rotation;

            {
                font = fonts.get(field.getFontName());

                if (font == null) {

                    FontName e = field.getFontName();
                    String name = null;

                    if (FontName.COURIER == e) {
                        name = BaseFont.COURIER;
                    } else if (FontName.COURIER_BOLD == e) {
                        name = BaseFont.COURIER_BOLD;
                    } else if (FontName.COURIER_BOLD_OBLIQUE == e) {
                        name = BaseFont.COURIER_BOLDOBLIQUE;
                    } else if (FontName.COURIER_OBLIQUE == e) {
                        name = BaseFont.COURIER_OBLIQUE;
                    } else if (FontName.HELVETICA == e) {
                        name = BaseFont.HELVETICA;
                    } else if (FontName.HELVETICA_BOLD == e) {
                        name = BaseFont.HELVETICA_BOLD;
                    } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_BOLDOBLIQUE;
                    } else if (FontName.HELVETICA_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_OBLIQUE;
                    } else if (FontName.TIMES_BOLD == e) {
                        name = BaseFont.TIMES_BOLD;
                    } else if (FontName.TIMES_BOLD_ITALIC == e) {
                        name = BaseFont.TIMES_BOLDITALIC;
                    } else if (FontName.TIMES_ITALIC == e) {
                        name = BaseFont.TIMES_ITALIC;
                    } else if (FontName.TIMES_ROMAN == e) {
                        name = BaseFont.TIMES_ROMAN;
                    }

                    if (name == null) {
                        throw new RuntimeException("Unknown font type: " + e);
                    }

                    font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                    fonts.put(field.getFontName(), font);
                }

                fontSize = field.getFontSize();

                if (TextAlignment.LEFT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_LEFT;
                } else if (TextAlignment.CENTER == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_CENTER;
                } else if (TextAlignment.RIGHT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_RIGHT;
                } else {
                    alignment = PdfContentByte.ALIGN_LEFT;
                }

                Object value = p.eval(field.getExpr());

                if (value == null) {
                    text = "";
                } else {
                    text = value.toString();
                }

                x = field.getX() * POINTS_IN_A_CM;
                y = field.getY() * POINTS_IN_A_CM;

                rotation = 0;
            }

            cb.beginText();

            cb.setFontAndSize(font, fontSize);

            cb.showTextAligned(alignment, text, x, y, rotation);

            cb.endText();
        }

        document.newPage();
    }

    reader.close();
    document.close();
}

From source file:com.mycompany.controller.catalog.PDFController.java

License:Apache License

@RequestMapping(value = ("/createPDF"), method = RequestMethod.GET)
public void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {/*from   ww  w .j a v  a 2 s  .co  m*/
        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
        Document document = new Document(PageSize.A4, 36, 72, 108, 180);
        PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Bharath\\Desktop\\bharath1.pdf"));
        document.open();
        Map<String, String[]> map = (Map<String, String[]>) context.getRequest().getParameterMap();
        Iterator<Map.Entry<String, String[]>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String[]> pairs = (Map.Entry<String, String[]>) it.next();
            document.add(new Paragraph(Arrays.toString(pairs.getValue())));
            it.remove(); // avoids a ConcurrentModificationException
        }
        document.close();
        System.out.println("converted to HTML");
    } catch (Exception e) {
        e.printStackTrace();
    }
    File downloadFile = new File("C:\\Users\\Bharath\\Desktop\\bharath1.pdf");
    FileInputStream inputStream = new FileInputStream(downloadFile);
    response.setContentType("application/pdf");
    response.setContentLength((int) downloadFile.length());
    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);
    OutputStream outStream = response.getOutputStream();
    System.out.println("9");
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;
    System.out.println("10");
    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }
    inputStream.close();
    outStream.close();
    response.flushBuffer();
    boolean success = (new File("C:\\Users\\Bharath\\Desktop\\bharath1.pdf")).delete();
}

From source file:com.mycompany.devman.domain.Raport.java

public static void main(String[] args) {

    Document document = new Document(); // Tworzymy dokument

    //* Ustawianie rozmiarw dokumentu
    Rectangle rect = new Rectangle(PageSize.A4); //Tworzenie elementu - rozmiaru dokumentu, ktry bdzie kwadratem o rozmiarze 210mm x 297mm - format a4
    // Utilities.millimetersToPoints(210), Utilities.millimetersToPoints(297)
    document.setPageSize(rect);//www. j a v a  2  s. co m

    Font[] fonts = { new Font(), new Font(Font.HELVETICA, 14, Font.NORMAL) };

    try { //Blok Try jest po to poniewa nie zawsze moemy mie miejsce tam gdzie chcemy zapisa pdf
        PdfWriter.getInstance(document, new FileOutputStream("raport.pdf"));

        document.open(); //Otwarcie dokumentu - teraz moemy do niego wsadza co kolwiek chcemy
        Paragraph paragraph = new Paragraph();
        paragraph.add("Raport");
        document.add(paragraph); //dodanie paragrafu do dokumentu
        document.close();
    } catch (Exception e) {
        e.printStackTrace(); // Wywietli error
    }

}

From source file:com.neu.cloud.Controller.FifthUseCaseController.java

public void generateReports(List<ArrayList<User>> user1ReportList)
        throws DocumentException, FileNotFoundException {
    Date date;/*from  w w w  .  jav  a2s  .c  o m*/
    String dateForFolder = String.valueOf(new Date());
    for (ArrayList<User> users : user1ReportList) {
        date = new Date();
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        //            String path = System.getProperty("user.dir") + "\\reports\\";
        String path = System.getProperty("user.dir") + "//";
        String fileName = "ITextTest" + date.getTime() + ".pdf";
        //            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path + "ITextTest" + date.getTime() + ".pdf"));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path + fileName));
        document.open();
        Table table = new Table(4);
        table.addCell("userID");
        table.addCell("username");
        table.addCell("password");
        table.addCell("productName");
        boolean flag = false;
        for (User u : users) {
            System.out.print("1");
            System.out.print("1");
            System.out.print("1");
            System.out.print("1");
            if (flag)
                continue;
            flag = true;
            table.addCell(String.valueOf(u.getUserID()));
            table.addCell(u.getUsername());
            table.addCell(u.getPassword());
            table.addCell(u.getProductName());
        }
        document.add(table);
        document.close();

        uploadInS3(path, fileName, dateForFolder);

        File file = new File(path + fileName);
        if (file.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation is failed.");
        }
    }
}

From source file:com.neu.cloud.Controller.FirstUseCaseController.java

public void generateReports(List<ArrayList<User>> user1ReportList)
        throws DocumentException, FileNotFoundException {
    Date date;//from  w  ww  . j  av  a  2 s  .com
    String dateForFolder = String.valueOf(new Date());
    for (ArrayList<User> users : user1ReportList) {
        date = new Date();
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        //            String path = System.getProperty("user.dir") + "\\reports\\";
        String path = System.getProperty("user.dir") + "//";
        String fileName = "ITextTest" + date.getTime() + ".pdf";
        //            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path + "ITextTest" + date.getTime() + ".pdf"));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path + fileName));
        document.open();
        Table table = new Table(4);
        table.addCell("userID");
        table.addCell("username");
        table.addCell("password");
        table.addCell("productName");
        for (User u : users) {
            table.addCell(String.valueOf(u.getUserID()));
            table.addCell(u.getUsername());
            table.addCell(u.getPassword());
            table.addCell(u.getProductName());
        }
        document.add(table);
        document.close();

        uploadInS3(path, fileName, dateForFolder);

        File file = new File(path + fileName);
        if (file.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation is failed.");
        }
    }
}

From source file:com.nokia.s60tools.swmtanalyser.wizards.ReportCreationJob.java

License:Open Source License

protected IStatus run(IProgressMonitor monitor) {

    monitor.beginTask("Creating report...", 10);

    try {//from   w  ww  .ja va 2s .c o m
        //Instantiation of document object
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(this.fileName));
        document.open();

        addGeneralDetails(document);

        if (!this.isOverviewReport) //If the report type is 1. i.e., report for selected issues only.
        {
            addSelectedIssuesReport(document);
        } else // If the report type is 2. i.e., Overview report
        {
            addOverviewReport(document);
        }

        addComments(document);

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

    } catch (DocumentException e) {
        e.printStackTrace();
        SwmtAnalyserPlugin.getConsole().println("Unable to write document, error was: '" + e + "'",
                IConsolePrintUtility.MSG_ERROR);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        SwmtAnalyserPlugin.getConsole().println("Unable to write document, error was: '" + e + "'",
                IConsolePrintUtility.MSG_ERROR);
    } catch (Exception e) {
        e.printStackTrace();
        AbstractProductSpecificConsole absConsole = (AbstractProductSpecificConsole) SwmtAnalyserPlugin
                .getConsole();
        absConsole.printStackTrace(e);
        SwmtAnalyserPlugin.getConsole().println("Unable to write document, error was: '" + e + "'",
                IConsolePrintUtility.MSG_ERROR);
    }
    return Status.OK_STATUS;
}

From source file:com.openkm.util.DocConverter.java

License:Open Source License

/**
 * Convert SRC to PDF/*from   www  .ja  va  2 s  .co m*/
 */
public void src2pdf(File input, File output, String lang)
        throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from SRC to PDF **");
    FileOutputStream fos = null;
    FileInputStream fis = null;

    try {
        fos = new FileOutputStream(output);
        fis = new FileInputStream(input);

        // Make syntax highlight
        String source = IOUtils.toString(fis);
        JaSHi jashi = new JaSHi(source, lang);
        // jashi.EnableLineNumbers(1);
        String parsed = jashi.ParseCode();

        // Make conversion to PDF
        Document doc = new Document(PageSize.A4.rotate());
        PdfWriter.getInstance(doc, fos);
        doc.open();
        HTMLWorker html = new HTMLWorker(doc);
        html.parse(new StringReader(parsed));
        doc.close();
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.openkm.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion//from www . j a v  a 2 s .  c o m
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        // int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                // doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                // ++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:com.openkm.util.PDFUtils.java

License:Open Source License

/**
 * Generate sample PDF//from   w  w w .ja va  2s  .co m
 */
public static void generateSample(int paragraphs, OutputStream os) throws DocumentException {
    LoremIpsum li = new LoremIpsum();
    Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
    PdfWriter.getInstance(doc, os);
    doc.open();

    for (int i = 0; i < paragraphs; i++) {
        doc.add(new Paragraph(li.getParagraphs()));
    }

    doc.close();
}