Example usage for com.lowagie.text.pdf PdfWriter getInstance

List of usage examples for com.lowagie.text.pdf PdfWriter getInstance

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getInstance.

Prototype


public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:com.matic.sudoku.io.export.PdfExporter.java

License:Open Source License

/**
 * Generate and export multiple boards to PDF
 * //from w  w w  . j  a v a2s. co  m
 * @param exporterParameters PDF exporter parameters
 * @param generator Generator used for puzzle generation
 * @throws IOException If any PDF library error occurs
 * @throws DocumentException If any error occurs while writing the PDF file
 */
public void write(final ExporterParameters exporterParameters, final Generator generator,
        final int boardDimension) throws IOException, DocumentException {
    //How many PDF-pages are needed to fit all puzzles using the desired page formatting
    final int optimisticPageCount = exporterParameters.getPuzzleCount()
            / exporterParameters.getPuzzlesPerPage();
    final int pageCount = exporterParameters.getPuzzleCount() % exporterParameters.getPuzzlesPerPage() > 0
            ? optimisticPageCount + 1
            : optimisticPageCount;

    final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN,
            DOCUMENT_MARGIN);
    final OutputStream outputStream = new FileOutputStream(exporterParameters.getOutputPath());
    final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);

    final String creator = Sudoku.getNameAndVersion();
    document.addSubject("Puzzles generated by " + creator);
    document.addCreator(creator);
    document.open();

    final Rectangle pageSize = document.getPageSize();
    final int pageHeight = (int) pageSize.getHeight();
    final int pageWidth = (int) pageSize.getWidth();

    //Get appropriate number of rows and columns needed to divide a page into
    final int horizontalDimension = exporterParameters.getPuzzlesPerPage() > 2 ? 2 : 1;
    final int verticalDimension = exporterParameters.getPuzzlesPerPage() > 1 ? 2 : 1;

    //Get available space for each board (with margins) on a page
    final int boardWidth = pageWidth / horizontalDimension;
    final int boardHeight = pageHeight / verticalDimension;

    final Board board = new Board(boardDimension, SymbolType.DIGITS);
    board.setSize(boardWidth, boardHeight);
    board.handleResized();

    //Get available height/width on a page for a puzzle itself
    final int puzzleWidth = board.getPuzzleWidth();
    int puzzlesPrinted = 0;

    final PdfContentByte contentByte = pdfWriter.getDirectContent();
    final Grading[] gradings = getGeneratedPuzzleGradings(exporterParameters.getGradings(),
            exporterParameters.getOrdering(), exporterParameters.getPuzzleCount());

    pageCounter: for (int page = 0; page < pageCount; ++page) {
        document.newPage();
        final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight);
        for (int y = 0, i = 0; i < verticalDimension; y += boardHeight, ++i) {
            for (int x = 0, j = 0; j < horizontalDimension; x += boardWidth, ++j) {
                //Check whether to generate a new puzzle or print empty boards 
                final ExportMode exportMode = exporterParameters.getExportMode();
                final Grading selectedGrading = exportMode == ExportMode.BLANK ? null
                        : gradings[puzzlesPrinted];
                if (exportMode == ExportMode.GENERATE_NEW) {
                    board.setPuzzle(generatePuzzle(generator, getSymmetry(exporterParameters.getSymmetries()),
                            selectedGrading));
                    board.recordGivens();
                }

                //Calculate puzzle drawing origins
                final int originX = x + (int) (boardWidth / 2 - (puzzleWidth / 2));
                final int originY = y + (int) (boardHeight / 2) - (puzzleWidth / 2);

                board.setSymbolType(getSymbolType(exporterParameters.getSymbolType()));
                board.setDrawingOrigin(originX, originY);
                board.draw(g2d, false, false);

                drawLegend(g2d,
                        getLegendString(exporterParameters.isShowNumbering(),
                                exporterParameters.isShowGrading(), puzzlesPrinted + 1, selectedGrading),
                        originX, originY, puzzleWidth);

                if (++puzzlesPrinted == exporterParameters.getPuzzleCount()) {
                    //We've printed all puzzles, break
                    g2d.dispose();
                    break pageCounter;
                }
            }
        }
        g2d.dispose();
    }
    document.close();
    outputStream.flush();
    outputStream.close();
}

From source file:com.mitchell.services.business.partialloss.assignmentdelivery.handler.ndu.util.AssignmentEmailDeliveryUtils.java

public void createPDF(final String content, final String path) throws Exception {

    // Create the PDF Document

    // step 1: creation of a document-object
    com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.LETTER, 36, 36, 36, 36);

    // step 2://  w  ww.  j  a  v a2 s  .  c  om
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.getInstance(document, new java.io.FileOutputStream(path));

    // step 3: we open the document
    document.open();

    // step 4:
    document.setMargins(36, 36, 36, 36);
    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_LEFT);
    paragraph.add(content);
    document.add(paragraph);

    // step 5: we close the document
    document.close();
}

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();/*from w ww. ja v  a2 s  . c  o m*/

    PdfContentByte cb = writer.getDirectContent();

    Check check = new Check();
    check.defaultFont = BaseFont.createFont("Helvetica", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.defaultFontSize = 8;
    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();/*from   ww  w.j a va 2  s. c  om*/

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

        PdfContentByte cb = writer.getDirectContent();

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

        /*
         * 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  w  w w.j  av  a  2  s. c  o 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);//from   w w  w.ja va  2 s. c om

    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   ww  w  . j  a  va  2 s .  c  om
    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;// w  w w.ja  v a2  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. j av  a2 s  . c  om
        //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.ny.apps.exporter.PdfExportBuilder.java

License:Open Source License

@Override
public void export(Object o) {
    System.out.println(o + " received message.");

    try {/*from w  w  w.  ja  va2  s. com*/
        document = new Document();

        PdfWriter.getInstance(document, new FileOutputStream(new File("E:\\ny.pdf")));

        document.open();

        document.add(new Paragraph("Hello " + o));
    } catch (FileNotFoundException e) {
        // TODO ? catch ?
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO ? catch ?
        e.printStackTrace();
    } finally {
        System.out.println("export complete.");
        document.close();
    }
}