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.mycom.products.mywebsite.backend.util.DownloadHandler.java

License:Open Source License

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
protected final void downloadUserInformation(@PathVariable int id, HttpServletRequest request,
        final HttpServletResponse response) throws ServletException, BusinessException, DocumentException {
    UserBean user = userService.select(id, FetchMode.EAGER);
    if (user == null) {
        return;//from w  w w .j  a  v a2  s.  c o m
    }
    Document document = new Document();
    document.setMargins(70, 70, 20, 20);

    try {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + user.getName() + "_profile.pdf\"");
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        Image profileImage = null;
        try {
            profileImage = Image.getInstance(user.getContent().getFilePath());
        } catch (Exception e) {
            // e.printStackTrace();
        }
        if (profileImage != null) {
            profileImage.setAlignment(Image.MIDDLE | Image.TEXTWRAP);
            profileImage.setBorder(Image.BOX);
            profileImage.setBorderWidth(5);
            BaseColor bgcolor = WebColors.getRGBColor("#E5E3E3");
            profileImage.setBorderColor(bgcolor);
            profileImage.scaleToFit(100, 100);
            document.add(profileImage);
        }
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        // Adding Table Data
        PdfPTable table = new PdfPTable(2); // 2 columns.
        table.setWidthPercentage(100); // Width 100%
        table.setSpacingBefore(15f); // Space before table
        table.setSpacingAfter(15f); // Space after table

        // Set Column widths
        float[] columnWidths = { 1f, 2f, };
        table.setWidths(columnWidths);

        // Name
        setTableHeader("Name", table);
        setTableContent(user.getName(), table);

        // Gender
        setTableHeader("Gender", table);
        String gender = "Male";
        if (user.getGender() == Gender.FEMALE) {
            gender = "Female";
        }
        setTableContent(gender, table);

        // Age
        setTableHeader("Age", table);
        setTableContent("" + user.getAge(), table);

        // Date of Birth
        setTableHeader("DOB", table);
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        setTableContent(dateFormatter.format(user.getDob()), table);

        // Email
        setTableHeader("Email", table);
        setTableContent(user.getEmail(), table);

        // NRC
        setTableHeader("NRC", table);
        setTableContent(user.getNrc(), table);

        // Phone
        setTableHeader("Phone", table);
        setTableContent(user.getPhone(), table);

        // Roles
        String roleStr = "";
        List<RoleBean> roles = user.getRoles();
        if (roles != null && roles.size() > 0) {
            Iterator<RoleBean> itr = roles.iterator();
            while (itr.hasNext()) {
                RoleBean role = itr.next();
                roleStr += role.getName();
                if (itr.hasNext()) {
                    roleStr += ",";
                }
            }
        }
        setTableHeader("Role(s)", table);
        setTableContent(roleStr, table);

        // Address
        setTableHeader("Address", table);
        setTableContent(user.getAddress(), table);

        document.add(table);
        document.add(new Paragraph(new Date().toString()));

    } catch (Exception e) {
        e.printStackTrace();

    }
    document.close();
}

From source file:com.mycompany.bandaru_exam.accountDriver.java

/**
 * @param args the command line arguments
 *///from  w ww .java 2  s  . c o m
public static void main(String[] args)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {
    // TODO code application logic here
    ReadfromExcel rd = new ReadfromExcel();
    List<Account> accountList = rd.getAccountListFromExcel();
    for (Account a : accountList) {
        System.out.println(a.getFirstName());
        OutputStream file = new FileOutputStream(new File(a.getLastName() + ".pdf"));
        Document document = new Document();
        PdfWriter.getInstance(document, file);

        //Inserting Image in PDF
        Image image = Image.getInstance("logo.png");
        image.scaleAbsolute(600f, 100f);//image width,height

        //Now Insert Every Thing Into PDF Document
        document.open();//PDF document opened........                
        document.add(image);
        document.add(new Paragraph("Welcome! " + a.getFirstName() + " " + a.getLastName() + "!"));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("        " + "Below are your Account Details :"));
        document.add(new Paragraph("        " + "First Name:" + a.getFirstName()));
        document.add(new Paragraph("        " + "Last Name:" + a.getLastName()));
        document.add(new Paragraph("        " + "Account Number:" + a.getAccNumber()));
        document.add(new Paragraph("        " + "Account Balance:$" + a.getBalance()));
        document.close();
        file.close();
    }
}

From source file:com.mycompany.mavenproject1.Createpdf.java

public void createPDF(String pdfFilename) {

    Document doc = new Document();
    PdfWriter docWriter = null;/*ww  w . j a  v a  2 s .c om*/
    initializeFonts();

    try {
        String path = "C:\\Users\\Thaskioglu\\Downloads\\" + pdfFilename;
        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.addAuthor("FabulousCar");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("FabulousCar");
        doc.addTitle("Invoice");
        doc.setPageSize(PageSize.LETTER);

        doc.open();
        PdfContentByte cb = docWriter.getDirectContent();

        boolean beginPage = true;
        int y = 0;

        for (int i = 0; i < 100; i++) {
            if (beginPage) {
                beginPage = false;
                generateLayout(doc, cb);
                generateHeader(doc, cb);
                y = 615;
            }
            generateDetail(doc, cb, i, y);
            y = y - 15;
            if (y < 50) {
                printPageNumber(cb);
                doc.newPage();
                beginPage = true;
            }
        }
        printPageNumber(cb);

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }
}

From source file:com.mycompany.mavenproject1.HelloWorld.java

/**
 * Creates a PDF document.//from   w w  w .j  a v a 2  s.  c  o m
 * @param filename the path to the new PDF document
 * @throws    DocumentException 
 * @throws    IOException 
 */
public void createPdf(String filename) throws DocumentException, IOException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    document.add(new Paragraph("Hello World!"));
    // step 5
    document.close();
}

From source file:com.mycompany.mavenproject2.ItemHistoryController.java

@FXML
public void OnPrintButtonAction(ActionEvent a) {
    Document document = new Document();
    //JavaPdfHelloWorld jp=new JavaPdfHelloWorld();

    try {/*from   w w  w .  j  a  va  2  s .  com*/
        PdfWriter.getInstance(document, new FileOutputStream("javaHello.pdf"));

        document.open();
        document.add(new Paragraph("A Hello World PDF document."));

        document.close();

        final File file = new File(
                "C:/Users/Third Ev/Documents/NetBeansProjects/FinalDemo/src/finaldemo/Controller/javaHello.pdf");

        f4.getHostServices().showDocument(file.toURI().toString());

        // no need to close PDFwriter?
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:com.mycompany.mavenproject2.JavaPdfHelloWorld.java

public static void main(String[] args) {
    Document document = new Document();
    try {// w w  w.  j av a2  s  .c  o  m
        PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));

        document.open();
        document.add(new Paragraph("A Hello World PDF document."));
        document.close(); // no need to close PDFwriter?

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.mycompany.mavenproject2.VirtualkeyController.java

@FXML
public void handlePDFButtonAction(ActionEvent a) throws IOException, DocumentException {

    Document document = new Document();
    FileOutputStream f2 = new FileOutputStream(FILE1);
    PdfWriter.getInstance(document, f2);
    document.open();
    addMetaData(document);//  w w w .  j  a va 2 s  .co m
    addTitlePage(document);
    //      addContent(document);
    // document.close();
    /* PdfReader reader = new PdfReader("C:/Users/Third Ev/Downloads/my.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());*/
    /* PdfDecoder pdf = new PdfDecoder();
     pdf.openPdfFile("C:/Users/Third Ev/Downloads/my.pdf");*/
    /*  hostServices = getHostServices();
        hostServices.showDocument("C:/Users/Third Ev/Documents/NetBeansProjects/FinalDemo/src/finaldemo/Controller/iText.pdf");*/
    document.close();
    f2.close();
    final File file = new File("/home/drashti/MyDemo.pdf");

    f4.getHostServices().showDocument(file.toURI().toString());

}

From source file:com.mycompany.peram_inclassexam.WritePDFFile.java

public void createPDF(AccountDetails account)
        throws DocumentException, FileNotFoundException, BadElementException, IOException {

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    PdfWriter write = PdfWriter.getInstance(document,
            new FileOutputStream(account.getLastName() + "_output.pdf"));

    document.open();

    Image image = Image.getInstance("image.png");

    image.scaleToFit(450f, 1800f);/*  www.j  a  va 2s  .c  om*/

    document.add(image);
    document.add(new Paragraph(
            "--------------------------------------------------------------------------------------------------------------------------"));

    Paragraph welcomeParagraph = new Paragraph(
            "Welcome! " + account.getFirstName() + " " + account.getLastName() + "!");
    welcomeParagraph.setSpacingBefore(50);

    document.add(welcomeParagraph);

    String firstName = "First Name: " + account.getFirstName();
    String lastName = "Last Name: " + account.getLastName();
    String acctNumber = "Account Number: " + account.getAccountNo();
    String acctBalance = String.format("Account Balance: $%.1f", account.getAccountBalance());

    Paragraph detailsPara = new Paragraph("Below are your Account Details:\n" + firstName + "\n" + lastName
            + "\n" + acctNumber + "\n" + acctBalance);
    detailsPara.setIndentationLeft(30);
    detailsPara.setSpacingBefore(20);
    document.add(detailsPara);

    document.close();
    write.close();
}

From source file:com.nerdcastle.nazmul.filetest.MainActivity.java

private void createPdf() {
    try {//from w  ww .  j  a v  a2s . c  om
        Document document = new Document();
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/created_pdf");
        myDir.mkdirs();
        String fname = "FirstPdf.pdf";
        File file = new File(myDir, fname);
        //FileOutputStream out = new FileOutputStream(file);
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.netsteadfast.greenstep.bsc.command.KpiReportPdfCommand.java

License:Apache License

private String createPdf(Context context) throws Exception {
    BscReportPropertyUtils.loadData();//from   w w w  .  j  a  v  a2 s.com
    BscReportSupportUtils.loadExpression(); // 2015-04-18 add
    String visionOid = (String) context.get("visionOid");
    VisionVO vision = null;
    BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context);
    for (VisionVO visionObj : treeObj.getVisions()) {
        if (visionObj.getOid().equals(visionOid)) {
            vision = visionObj;
        }
    }
    FontFactory.register(BscConstants.PDF_ITEXT_FONT);
    String fileName = UUID.randomUUID().toString() + ".pdf";
    String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
    OutputStream os = new FileOutputStream(fileFullPath);
    //Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    document.left(100f);
    document.top(150f);
    PdfWriter writer = PdfWriter.getInstance(document, os);
    document.open();

    int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0)
            .getDateRangeScores().size();
    PdfPTable table = new PdfPTable(MAX_COLSPAN);
    PdfPTable dateRangeTable = new PdfPTable(dateRangeRows);
    PdfPTable chartsTable = new PdfPTable(2);
    PdfPTable signTable = new PdfPTable(1);
    table.setWidthPercentage(100f);
    dateRangeTable.setWidthPercentage(100f);
    chartsTable.setWidthPercentage(100f);
    signTable.setWidthPercentage(100f);

    this.createHead(table, vision);
    this.createBody(table, vision);
    this.createDateRange(dateRangeTable, vision, context, dateRangeRows);
    this.putCharts(chartsTable, context);
    this.putSignature(signTable, context);

    document.add(chartsTable);
    document.add(table);
    document.add(dateRangeTable);
    document.add(signTable);
    document.close();
    writer.close();

    os.flush();
    os.close();
    os = null;

    File file = new File(fileFullPath);
    String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file,
            "kpi-report.pdf");
    file = null;
    return oid;
}