Example usage for org.apache.pdfbox.pdmodel PDDocument save

List of usage examples for org.apache.pdfbox.pdmodel PDDocument save

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument save.

Prototype

public void save(OutputStream output) throws IOException 

Source Link

Document

This will save the document to an output stream.

Usage

From source file:com.mycompany.mavenproject4.NewMain.java

/**
 * @param args the command line arguments
 *//*from ww  w  .j  a v a  2  s  .  c  o  m*/
public static void main(String[] args) {
    PDDocument doc;
    doc = new PDDocument();
    doc.addPage(new PDPage());
    try {
        doc.save("Empty PDF.pdf");
        doc.close();
    } catch (Exception io) {
        System.out.println(io);
    }
}

From source file:com.openkm.extractor.PdfTextExtractor.java

License:Open Source License

/**
 * {@inheritDoc}/*from  w  w w. ja  va  2s  .c om*/
 */
@SuppressWarnings("rawtypes")
public String extractText(InputStream stream, String type, String encoding) throws IOException {
    try {
        PDFParser parser = new PDFParser(new BufferedInputStream(stream));

        try {
            parser.parse();
            PDDocument document = parser.getPDDocument();

            if (document.isEncrypted()) {
                try {
                    document.decrypt("");
                    document.setAllSecurityToBeRemoved(true);
                } catch (Exception e) {
                    throw new IOException("Unable to extract text: document encrypted", e);
                }
            }

            CharArrayWriter writer = new CharArrayWriter();
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setLineSeparator("\n");
            stripper.writeText(document, writer);
            String st = writer.toString().trim();
            log.debug("TextStripped: '{}'", st);

            if (Config.SYSTEM_PDF_FORCE_OCR || st.length() <= 1) {
                log.warn("PDF does not contains text layer");

                // Extract images from PDF
                StringBuilder sb = new StringBuilder();

                if (!Config.SYSTEM_PDFIMAGES.isEmpty()) {
                    File tmpPdf = FileUtils.createTempFile("pdf");
                    File tmpDir = new File(EnvironmentDetector.getTempDir());
                    String baseName = FileUtils.getFileName(tmpPdf.getName());
                    document.save(tmpPdf);
                    int pgNum = 1;

                    try {
                        for (PDPage page : (List<PDPage>) document.getDocumentCatalog().getAllPages()) {
                            HashMap<String, Object> hm = new HashMap<String, Object>();
                            hm.put("fileIn", tmpPdf.getPath());
                            hm.put("firstPage", pgNum);
                            hm.put("lastPage", pgNum++);
                            hm.put("imageRoot", tmpDir + File.separator + baseName);
                            String cmd = TemplateUtils.replace("SYSTEM_PDFIMAGES", Config.SYSTEM_PDFIMAGES, hm);
                            ExecutionUtils.runCmd(cmd);

                            for (File tmp : tmpDir.listFiles()) {
                                if (tmp.getName().startsWith(baseName + "-")) {
                                    if (page.findRotation() > 0) {
                                        ImageUtils.rotate(tmp, tmp, page.findRotation());
                                    }

                                    try {
                                        String txt = doOcr(tmp);
                                        sb.append(txt).append(" ");
                                        log.debug("OCR Extracted: {}", txt);
                                    } finally {
                                        FileUtils.deleteQuietly(tmp);
                                    }
                                }
                            }
                        }
                    } finally {
                        FileUtils.deleteQuietly(tmpPdf);
                    }
                } else {
                    for (PDPage page : (List<PDPage>) document.getDocumentCatalog().getAllPages()) {
                        PDResources resources = page.getResources();
                        Map<String, PDXObject> images = resources.getXObjects();

                        if (images != null) {
                            for (String key : images.keySet()) {
                                PDXObjectImage image = (PDXObjectImage) images.get(key);
                                String prefix = "img-" + key + "-";
                                File pdfImg = null;

                                try {
                                    pdfImg = File.createTempFile(prefix, ".png");
                                    log.debug("Writing image: {}", pdfImg.getPath());

                                    // Won't work until PDFBox 1.8.9
                                    ImageIO.write(image.getRGBImage(), "png", pdfImg);

                                    if (page.findRotation() > 0) {
                                        ImageUtils.rotate(pdfImg, pdfImg, page.findRotation());
                                    }

                                    // Do OCR
                                    String txt = doOcr(pdfImg);
                                    sb.append(txt).append(" ");
                                    log.debug("OCR Extracted: {}", txt);
                                } finally {
                                    FileUtils.deleteQuietly(pdfImg);
                                }
                            }
                        }
                    }
                }

                return sb.toString();
            } else {
                return writer.toString();
            }
        } finally {
            try {
                PDDocument doc = parser.getPDDocument();
                if (doc != null) {
                    doc.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    } catch (Exception e) {
        // it may happen that PDFParser throws a runtime
        // exception when parsing certain pdf documents
        log.warn("Failed to extract PDF text content", e);
        throw new IOException(e.getMessage(), e);
    } finally {
        stream.close();
    }
}

From source file:com.PDF.Resume.java

public ByteArrayOutputStream createResume() throws ParseException, IOException, COSVisitorException {
    System.out.println(imagePath);

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    // PDPage.PAGE_SIZE_LETTER is also possible
    PDRectangle rect = page1.getMediaBox();
    // rect can be used to get the page width and height
    document.addPage(page1);/*w  w  w  .j  av  a2  s. co  m*/

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    int line = 0;

    // Define a text content stream using the selected font, move the cursor and draw some text
    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
    cos.drawString("Pagina " + ++pagenumber);
    cos.endText();
    line--;

    cos.beginText();
    cos.setFont(fontPlain, 24);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 90 * (++line));
    cos.drawString("Curriculum Vitae");
    cos.endText();

    if (user != null) {
        cos.beginText();
        cos.setFont(fontPlain, 24);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 90 * (++line));
        cos.drawString(user.getSurname() + "");
        cos.endText();
    }

    // add an image
    try {
        BufferedImage awtImage = ImageIO.read(new File(
                "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 1f; // alter this value to set the image size
        cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
    } catch (FileNotFoundException fnfex) {
        System.out.println("No image for you");
    }
    // Make sure that the content stream is closed:
    cos.close();

    //second page
    line = 0;
    PDPage page2 = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page2);
    cos = new PDPageContentStream(document, page2);

    try {
        BufferedImage awtImage = ImageIO.read(new File(
                "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 1f; // alter this value to set the image size
        cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
    } catch (FileNotFoundException fnfex) {
        System.out.println("No image for you");
    }

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
    cos.drawString("Pagina " + ++pagenumber);
    cos.endText();

    line--;

    cos.beginText();
    cos.setFont(fontPlain, 18);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 90 * (++line));
    cos.drawString("Personalia");
    cos.endText();
    line += 4;

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Naam:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getSurname() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Geslacht:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getGender() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Telefoonnummer:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getPersonalPhone() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Emailadres:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getPersonalEmail() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Adres:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getAddress() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Postcode:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getZipCode() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Stad:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getCity() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Provincie:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getRegion() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Functie:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getFunction() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Business Unit:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getBusinessUnitAsString() + "");
    cos.endText();

    if (!educationList.isEmpty()) {
        line++;
        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Opleidingen");
        cos.endText();
        for (EmployeeHasEducation e : educationList) {
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("School:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEducation().getSchool() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Richting:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEducation().getDegree() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Niveau:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEducation().getGrade() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Begindatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getStartDate().substring(0, 10) + "");

            cos.endText();
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Einddatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEndDate().substring(0, 10) + "");
            cos.endText();

        }
    }
    if (!certificateList.isEmpty()) {
        line++;
        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Certificaten");
        cos.endText();
        for (Certificate c : certificateList) {
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Certificaat naam:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getName() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Certificaat plaats:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getCertificationAuthority() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Licentienummer:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getLicenseNumber() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Startdatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getStartDate().substring(0, 10) + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Einddatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getExpirationDate().substring(0, 10) + "");
            cos.endText();
            line++;
        }
        line++;
    }

    cos.close();
    if (!preceedings.isEmpty()) {
        line = 0;
        PDPage page3 = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page3);
        cos = new PDPageContentStream(document, page3);

        try {
            BufferedImage awtImage = ImageIO.read(new File(
                    "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
            PDXObjectImage ximage = new PDPixelMap(document, awtImage);
            float scale = 1f; // alter this value to set the image size
            cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
        } catch (FileNotFoundException fnfex) {
            System.out.println("No image for you");
        }

        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
        cos.drawString("Pagina " + ++pagenumber);
        cos.endText();

        line--;

        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 100 * (++line));
        cos.drawString("Projecten");
        line += 4;
        cos.endText();

        for (Preceeding p : preceedings) {
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Projectnaam:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getName() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Bedrijfsnaam:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getCompany().getName() + " ");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Project rol:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getDescription() + "");
            cos.endText();
            //    }

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Startdatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getStartDate() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Einddatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getEndDate() + "");
            cos.endText();

            line++;
        }
    }
    cos.close();
    //Skills of the user
    if (!skillList.isEmpty()) {

        line = 0;
        PDPage page3 = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page3);
        cos = new PDPageContentStream(document, page3);

        try {
            BufferedImage awtImage = ImageIO.read(new File(
                    "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
            PDXObjectImage ximage = new PDPixelMap(document, awtImage);
            float scale = 1f; // alter this value to set the image size
            cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
        } catch (FileNotFoundException fnfex) {
            System.out.println("No image for you");
        }

        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
        cos.drawString("Pagina " + ++pagenumber);
        cos.endText();

        line--;

        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 100 * (++line));
        cos.drawString("Skills");
        cos.endText();
        line += 4;

        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Skill & Rating:");
        cos.endText();
        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Jaren ervaring:");
        cos.endText();
        line -= 2;
        for (SkillRating s : skillList) {

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (++line));
            cos.drawString(s.getSkill().getName() + " niveau " + s.getRating());
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (++line));
            cos.drawString("" + s.getExpYears());
            cos.endText();
            line++;
        }
    }

    cos.close();
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    document.save(output);

    document.close();

    return output;
}

From source file:com.projectlaver.util.VoucherService.java

License:Open Source License

File generateVoucherPdf(String pdfFilename, File barcodeImageFile, VoucherDTO dto) {

    // the result 
    File pdfFile = null;//from w w  w  .j  a  v  a  2 s .c o  m

    // the document
    PDDocument doc = null;
    try {
        // Create a new document and add a page to it
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        float pageWidth = page.getMediaBox().getWidth();
        float pageHeight = page.getMediaBox().getHeight();

        // For some reason this may need to happen after reading the image
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        /**
         * Read & draw the client logo
         */
        this.drawImageWithMaxEdge(contentStream, 15f, 629, 150,
                this.readImage(new URL(dto.getClientLogoUrl()), doc));

        /**
         *  Read & draw the barcode image
         */

        BufferedImage bim = ImageIO.read(barcodeImageFile);
        PDXObjectImage barcodeImage = new PDPixelMap(doc, bim);

        // inspired by http://stackoverflow.com/a/22318681/535646
        float barcodeScale = 1f; // reduce this value if the image is too large

        this.drawImage(contentStream, 206f, 315f, barcodeImage, barcodeScale);

        /** 
         * Read & draw the social eq logo image
         */

        float logoScale = 0.15f; // reduce this value if the image is too large
        this.drawImage(contentStream, 246f, 265f, this.readImage(new URL(this.socialEqLogoUrl), doc),
                logoScale);

        /**
         * Read & draw the client image
         */
        this.drawImageWithMaxEdge(contentStream, 0f, 145, 612,
                this.readImage(new URL(dto.getClientCampaignImageUrl()), doc));

        /**
         * Add some rectangles to the page to set off the sections
         */

        contentStream.setNonStrokingColor(new Color(0.82f, 0.82f, 0.82f, 0.6f)); // light grey

        /**
         *  around the merchant logo / title
         */

        contentStream.fillRect(0, pageHeight - 10, pageWidth, 10); // top edge
        contentStream.fillRect(0, pageHeight - 175, pageWidth, 10); // bottom edge
        contentStream.fillRect(0, pageHeight - 175, 10, 175); // left edge
        contentStream.fillRect(170, pageHeight - 175, 10, 175); // right of the logo
        contentStream.fillRect(pageWidth - 10, pageHeight - 175, 10, 175); // right edge

        // behind the terms and conditions
        contentStream.fillRect(0f, 0f, pageWidth, 145f);

        /**
         *  Handle the text
         */

        // text color is black
        contentStream.setNonStrokingColor(Color.BLACK);

        // merchant name
        this.printNoWrap(page, contentStream, 195, 712, dto.getMerchantName(), 48);

        // listing title
        this.printNoWrap(page, contentStream, 195, 662, dto.getVoucherTitle(), 24);

        // Long description
        this.printNoWrap(page, contentStream, 30, 582, "Details:", 14);

        PdfParagraph ld = new PdfParagraph(30, 562, dto.getVoucherDetails(), 14);
        this.printLeftAlignedWithWrap(contentStream, ld);

        // Terms and conditions
        this.printNoWrap(page, contentStream, 30, 115, "Terms & Conditions:", 12);

        PdfParagraph toc = new PdfParagraph(30, 100, dto.getVoucherTerms(), 10);
        this.printLeftAlignedWithWrap(contentStream, toc);

        // Make sure that the content stream is closed:
        contentStream.close();

        String pdfPath = System.getProperty("java.io.tmpdir") + pdfFilename;
        doc.save(pdfPath);

        pdfFile = new File(pdfPath);

    } catch (Exception e) {

        throw new RuntimeException("Could not create the PDF File.", e);

    } finally {
        if (doc != null) {

            try {
                doc.close();
            } catch (IOException e) {
                throw new RuntimeException("Could not close the PDF Document.", e);
            }
        }
    }

    return pdfFile;
}

From source file:com.przemo.pdfmanipulate.Application.java

public static void main(String[] arg) {

    try {//from  w  w  w  . jav  a  2  s .  c o m
        PDDocument doc = PDFBuilder.build("H:\\dra.pdf", FormularzBuilder.buildAndFill("H:\\zusdra2", "ZUS DRA",
                new FlatFileFormDataProvider("H:\\dra_dane")));
        if (doc != null) {
            doc.save("H:\\draY2.pdf");
        }
    } catch (IOException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.santaanna.friendlyreader.pdfstod.pdfstod3.ReplaceStringStreamEngine.java

License:Apache License

private void saveAndClose(String filnamn, PDDocument utfil) {
    try {/*  ww w  .  j  av a2 s  .co  m*/
        if (utfil != null) {
            SkrivUt(3, "saveAndClose");
            utfil.save(filnamn);
            utfil.close();
        }
    } catch (java.io.IOException jioio) {
        SkrivUt(7, "IO Fel i saveAndClose.");
    } catch (COSVisitorException cosv) {
        SkrivUt(7, "CosVis Fel i saveAndClose.");
    }
}

From source file:com.truckzoo.test.pdf.SuperimposePage.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*if (args.length != 2)
    {/*from w  ww.  java2 s  .c o  m*/
    System.err.println("usage: " + SuperimposePage.class.getName() +
            " <source-pdf> <dest-pdf>");
    System.exit(1);
    }*/
    String sourcePath = args[0];
    String destPath = args[1];

    PDDocument sourceDoc = null;
    try {
        // load the source PDF
        sourceDoc = PDDocument.load(new File(sourcePath));
        int sourcePage = 1;

        // create a new PDF and add a blank page
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // write some sample text to the new page
        PDPageContentStream contents = new PDPageContentStream(doc, page);
        contents.beginText();
        contents.setFont(PDType1Font.HELVETICA_BOLD, 12);
        contents.newLineAtOffset(2, PDRectangle.LETTER.getHeight() - 12);
        contents.showText("Sample text");
        contents.endText();

        // Create a Form XObject from the source document using LayerUtility
        LayerUtility layerUtility = new LayerUtility(doc);
        PDFormXObject form = layerUtility.importPageAsForm(sourceDoc, sourcePage - 1);

        // draw the full form
        contents.drawForm(form);

        // draw a scaled form
        contents.saveGraphicsState();
        Matrix matrix = Matrix.getScaleInstance(0.5f, 0.5f);
        contents.transform(matrix);
        contents.drawForm(form);
        contents.restoreGraphicsState();

        // draw a scaled and rotated form
        contents.saveGraphicsState();
        matrix.rotate(1.8 * Math.PI); // radians
        contents.transform(matrix);
        contents.drawForm(form);
        contents.restoreGraphicsState();

        contents.close();
        doc.save(destPath);
        doc.close();
    } finally {
        if (sourceDoc != null) {
            sourceDoc.close();
        }
    }
}

From source file:controladores3.controladorGenerarLiquidaciones.java

public boolean generarLiquidaciones()
        throws FileNotFoundException, TransformerException, IOException, FOPException {

    Thread runnable = new Thread() {
        public void run() {
            try {
                modeloFacturas rutas = new modeloFacturas();
                dfs.setCurrencySymbol("$ ");
                dfs.setGroupingSeparator('.');
                dfs.setMonetaryDecimalSeparator('.');
                ((DecimalFormat) FORMAT).setDecimalFormatSymbols(dfs);
                controladores.controladorPrincipal miControlador = new controladorPrincipal();
                modelos.modeloEmpleados liquidaciones = new modeloEmpleados();
                modelos3.modeloRemuneraciones remuneraciones = new modeloRemuneraciones();
                String[][] data = liquidaciones.obtenerRemuneraciones2(getMes(), getYear());
                String[][] imp2cat = remuneraciones.obtenerTablaImpuesto();
                //                    float uf = remuneraciones.obtenerUF() / 100;
                double uf = remuneraciones.obtenerUF();
                int numEmp = data.length;
                String path = "Liquidaciones " + per;
                File dir = new File(path);
                dir.mkdir();//from  w ww  .j  a v a 2s  .c om
                //                    int bono300 = miControlador.obtenerBono300();
                for (int i = 0; i < numEmp; i++) {
                    String fileName = path + "/" + data[i][0] + ".pdf"; // name of our file
                    try {
                        PDDocument doc = new PDDocument(); // creating instance of pdfDoc
                        PDPage page = new PDPage();
                        doc.addPage(page); // adding page in pdf doc file
                        int base = Integer.parseInt(data[i][2]) * Integer.parseInt(data[i][28]) / 30;
                        //GRATIFICACION
                        int grat = (int) (base * 0.25);
                        //BONO ANTIGUEDAD
                        int bonoAnt = miControlador.obtenerBonoAnt(data[i][5]);
                        //BONO 300
                        //                            int totalBon300 = bono300 * Integer.parseInt(data[i][9]);
                        int totalBon300 = Integer.parseInt(data[i][27]);
                        //BONO ADICIONAL
                        int bonoAd = Integer.parseInt(data[i][11]);
                        //BONO RESPONSABILIDAD
                        int bonoResp = 0;
                        //BONO ADICIONAL
                        double bonoCol1 = Double.parseDouble(data[i][8]);
                        double bonoCol30 = Double.parseDouble(data[i][9]);
                        double bonoCol = bonoCol1 + bonoCol30 / 2;
                        int totalBonCol = (int) Math.round(((double) base * 0.0077777) * bonoCol);
                        //HORAS EXTRA
                        double horasExNor = Double.parseDouble(data[i][12]);
                        double horasExFes = Double.parseDouble(data[i][13]);
                        double horasEx = 0;
                        double bonoHor = 0;
                        double cantHorEx = 0;
                        //total de horas extras normales = 1; festivas = 2
                        double totalHorex = 0;
                        double resHorEx = 0;
                        if (horasExNor > 45) {
                            cantHorEx = 45;
                            totalHorex = 45;
                            resHorEx = horasExNor - 45;
                        } else {
                            cantHorEx = horasExNor;
                            totalHorex = cantHorEx;
                        }
                        if (cantHorEx + horasExFes > 45) {
                            resHorEx = resHorEx + (horasExFes - 45 + cantHorEx) * 2;
                            totalHorex = 45 - cantHorEx;
                            cantHorEx = 45;
                        } else {
                            cantHorEx += horasExFes;
                            totalHorex += horasExFes * 2;
                        }

                        //BONO ASIGNACION VOLUNTARIA
                        double totalBonoAV = base * 0.0077777 * resHorEx;
                        double valorHorEx = (int) ((double) base * 0.0077777 * totalHorex);
                        //TOTAL IMPONIBLE
                        double totImp = base + grat + bonoAnt + bonoAd + bonoResp + totalBonoAV + totalBonCol
                                + totalBon300 + valorHorEx;
                        //DESCUENTO AFP
                        int descAFP = Integer.parseInt(data[i][21]);
                        int totalAFP = (int) (totImp * ((double) descAFP / 10000));
                        int sis = (int) (totImp * 0.0141);
                        //DESCUENTO SALUD
                        double descSalud = 0, totalSalud = 0;
                        String salud;
                        if (data[i][4].toLowerCase().compareTo("fonasa") == 0) {
                            salud = "FONASA";
                            descSalud = Integer.parseInt(data[i][22]);
                            totalSalud = (int) (totImp * ((double) descSalud / 10000));
                        } else {
                            if (data[i][23].compareTo("") == 0) {
                                salud = data[i][4];
                            } else {
                                salud = data[i][23];
                            }
                            descSalud = ((double) Integer.parseInt(data[i][24]) / 1000) * uf;
                            totalSalud = descSalud;
                        }
                        //DESCUENTO CESANTIA
                        int ces = (int) (totImp * 0.006);
                        int cesEmp = (int) (totImp * 0.024);
                        //DESCUENTOS LEGALES
                        double descLegales = ces + totalSalud + totalAFP;
                        //TOTAL TRIBUTABLE
                        double totTrib = totImp - totalAFP - totalSalud - ces;
                        int descRenta = 0;
                        double totAux = 0;
                        for (String[] imp2cat1 : imp2cat) {
                            if (totTrib > Float.parseFloat(imp2cat1[0]) / 10
                                    && totTrib <= Float.parseFloat(imp2cat1[1]) / 10) {
                                descRenta = (int) (totTrib * Float.parseFloat(imp2cat1[2]) / 1000
                                        - Float.parseFloat(imp2cat1[3]) / 100);
                                totAux = totTrib - descRenta;
                                break;
                            }
                        }
                        //CAJA COMPENSACION
                        int caja = Integer.parseInt(data[i][15]);
                        //ASIGNACION FAMILIAR
                        int af = Integer.parseInt(data[i][16]);
                        //LIQ ALCANZADO
                        double liqAl = totAux - caja;
                        //COLACION 
                        int col = Integer.parseInt(data[i][6]);
                        //TRANSPORTE
                        int trans = Integer.parseInt(data[i][7]);
                        //TOTAL NO IMPONIBLE
                        int noImp = trans + col + af;
                        //ANTICIPO ADELANTO PRESTAMOS
                        int antic = Integer.parseInt(data[i][17]);
                        int adel = Integer.parseInt(data[i][18]);
                        int pres = Integer.parseInt(data[i][19]);
                        int cuo = Integer.parseInt(data[i][20]);
                        int cuoPres = 0;
                        int cuores = Math.max(0, Integer.parseInt(data[i][26]) - 1);
                        if (cuo != 0) {
                            cuoPres = pres / cuo;
                        }
                        //DESCUENTOS MENSUALES
                        int descMensuales = caja + antic + adel + cuoPres + descRenta;
                        //TOTAL HABERES
                        double totalHaberes = noImp + totImp;
                        //TOTAL DESCUENTOS
                        int totDesc = antic + adel + cuoPres + caja;
                        //LIQUIDO
                        double liq = liqAl + col + trans + af - antic - adel - cuoPres;

                        PDPageContentStream content = new PDPageContentStream(doc, page);

                        //HEADER

                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 10);
                        content.setLeading(14.5f);
                        content.moveTextPositionByAmount(50, 770);
                        content.showText("GRUAS SANTA TERESITA LTDA.");
                        content.newLineAtOffset(200, 0);
                        content.showText("LIQUIDACIN TRABAJADOR");
                        content.newLineAtOffset(200, 0);
                        content.showText(per);
                        content.newLineAtOffset(-400, 0);
                        content.newLine();
                        content.showText("77.037.960-1");
                        content.newLine();
                        content.newLine();
                        content.showText("Nombre: " + data[i][1]);
                        content.newLineAtOffset(400, 0);
                        content.showText("Contrato: " + data[i][25]);
                        content.newLineAtOffset(-400, 0);
                        content.newLine();
                        content.showText("Rut: " + data[i][0]);
                        content.endText();
                        content.drawLine(30, 700, 600, 700);

                        //LEFT SIDE

                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 9);
                        content.setLeading(14.5f);
                        content.moveTextPositionByAmount(120, 650);
                        content.showText("HABERES");
                        content.endText();
                        content.drawLine(45, 645, 245, 645);

                        content.beginText();
                        content.moveTextPositionByAmount(50, 635);
                        content.showText("Sueldo base proporcional");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(base));
                        content.newLineAtOffset(-150, -15);
                        double horex = Double.parseDouble(data[i][13]);
                        if (horex > 45) {
                            horex = 45;
                        }
                        content.showText("Horas extra ( " + cantHorEx + " horas )");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(valorHorEx));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Gratificacin:");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(grat));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono aos trabajados");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(bonoAnt));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono horas");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalBon300));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono asignacin voluntaria");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalBonoAV));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono adicional");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalBonCol));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Otros bonos");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(bonoAd));
                        content.endText();

                        content.drawLine(45, 515, 245, 515);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 500);
                        content.showText("Imponible");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totImp));
                        content.newLineAtOffset(-150, -15);
                        content.endText();
                        content.drawLine(45, 493, 245, 493);

                        content.beginText();
                        content.moveTextPositionByAmount(50, 470);
                        content.showText("Colacin");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(col));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Transporte");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(trans));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Asignacin familiar");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(af));
                        content.endText();

                        content.drawLine(45, 425, 245, 425);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 410);
                        content.showText("No imponible");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(noImp));
                        content.endText();
                        content.drawLine(45, 403, 245, 403);

                        content.drawLine(45, 380, 245, 380);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 365);
                        content.showText("Total haberes");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalHaberes));
                        content.endText();

                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 9);
                        content.setLeading(14.5f);
                        content.moveTextPositionByAmount(65, 280);
                        content.showText("APORTES LEGALES EMPLEADOR");
                        content.endText();
                        content.drawLine(45, 275, 245, 275);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 265);
                        content.showText("SIS");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(sis));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Seguro de cesanta empleador");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(cesEmp));
                        content.endText();
                        content.drawLine(45, 243, 245, 243);

                        //RIGHT SIDE
                        content.beginText();
                        content.moveTextPositionByAmount(410, 650);
                        content.showText("DESCUENTOS");
                        content.endText();
                        content.drawLine(345, 645, 545, 645);

                        content.beginText();
                        content.moveTextPositionByAmount(350, 635);
                        content.showText("Descuento AFP");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalAFP));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Descuento salud");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalSalud));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Seguro de cesanta trabajador");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(ces));
                        content.endText();

                        content.drawLine(345, 585, 545, 585);
                        content.beginText();
                        content.moveTextPositionByAmount(350, 570);
                        content.showText("Descuentos legales");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descLegales));
                        content.endText();
                        content.drawLine(345, 563, 545, 563);

                        content.beginText();
                        content.moveTextPositionByAmount(350, 545);
                        content.showText("Impuesto a la renta");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descRenta));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Caja de compensacin");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(caja));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Anticipo");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(antic));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Adelanto");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(adel));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Prstamo");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(cuoPres));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Cuotas restantes");
                        content.newLineAtOffset(150, 0);
                        content.showText(String.valueOf(cuores));
                        content.endText();

                        content.drawLine(345, 455, 545, 455);
                        content.beginText();
                        content.moveTextPositionByAmount(350, 440);
                        content.showText("Descuentos mensuales");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descMensuales));
                        content.endText();
                        content.drawLine(345, 433, 545, 433);

                        content.drawLine(345, 400, 545, 400);
                        content.beginText();
                        content.moveTextPositionByAmount(350, 385);
                        content.showText("Total descuentos");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descLegales + descMensuales));
                        content.endText();
                        content.drawLine(345, 378, 545, 378);

                        //CENTER
                        content.drawLine(180, 335, 400, 335);
                        content.beginText();
                        content.moveTextPositionByAmount(190, 320);
                        content.showText("Total a pago");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(liq));
                        content.endText();
                        content.drawLine(180, 313, 400, 313);

                        content.close();
                        doc.save(fileName); // saving as pdf file with name perm 
                        doc.close(); // cleaning memory       

                    } catch (IOException e) {
                        System.out.println(e.getMessage());
                    }
                }
                JOptionPane.showMessageDialog(null, "Liquidaciones de sueldo generadas con xito",
                        "Operacin exitosa", JOptionPane.INFORMATION_MESSAGE);
                //                    liquidaciones.limpiarRemuneraciones();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    //runnable.run();
    runnable.start();
    return true;
}

From source file:controladores4.controladorReportes.java

public boolean generarInformeCobranza(final JTable tabla, final int[] rows) {
    DateFormat perDate = new SimpleDateFormat("MMMM-yyyy");
    DateFormat date = new SimpleDateFormat("dd-MM-yyyy");
    final String per = date.format(new Date());
    final NumberFormat FORMAT = NumberFormat.getCurrencyInstance();
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    Thread runnable = new Thread() {
        public void run() {
            try {
                dfs.setCurrencySymbol("$ ");
                dfs.setGroupingSeparator('.');
                dfs.setMonetaryDecimalSeparator('.');
                ((DecimalFormat) FORMAT).setDecimalFormatSymbols(dfs);
                String path = "Informes de cobranza/" + tabla.getValueAt(rows[0], 2);
                File dir = new File(path);
                dir.mkdirs();/*from  ww w.j  a va  2s .com*/
                String fileName = path + "/" + per + ".pdf"; // name of our file
                PDDocument doc = new PDDocument();
                PDPage page = new PDPage();
                doc.addPage(page);
                PDPageContentStream content = new PDPageContentStream(doc, page);
                int total = 0;
                modeloClientes model = new modeloClientes();
                String[] data = model.obtenerRutContactoPorRazon(tabla.getValueAt(rows[0], 2).toString());
                try {
                    //HEADER
                    content.beginText();
                    content.setFont(PDType1Font.HELVETICA, 10);
                    content.setLeading(14.5f);
                    content.moveTextPositionByAmount(50, 770);
                    content.endText();

                    content.drawLine(30, 750, 600, 750);
                    File imagen = new File(("src/icono/Logo_Gruas.bmp"));
                    String imPath = imagen.getAbsolutePath();
                    System.out.println(imPath);
                    PDImageXObject image = PDImageXObject.createFromFile(imPath, doc);
                    content.drawImage(image, 50, 600);

                    content.beginText();
                    content.moveTextPositionByAmount(400, 680);
                    content.showText("INFORME COBRANZA");
                    content.newLine();
                    content.showText(per);
                    content.newLineAtOffset(-130, -80);
                    content.showText("CLIENTE");
                    content.newLine();
                    content.endText();

                    content.drawLine(30, 580, 600, 580);

                    content.beginText();
                    content.moveTextPositionByAmount(50, 560);
                    content.showText("Rut: ");
                    content.newLineAtOffset(100, 0);
                    content.showText(data[0]);
                    content.newLineAtOffset(-100, -15);
                    content.showText("Razn Social:");
                    content.newLineAtOffset(100, 0);
                    content.showText(data[1]);
                    content.newLineAtOffset(-100, -15);
                    content.showText("Contacto:");
                    content.newLineAtOffset(100, 0);

                    content.newLine();
                    content.endText();

                    content.drawLine(30, 510, 600, 510);

                    content.beginText();
                    content.moveTextPositionByAmount(50, 480);
                    content.showText(
                            "Estimado cliente, las facturas que se exponen a continuacin se encuentran pendientes");
                    content.newLine();
                    content.showText("de pago. Favor regularizar la situacin.");
                    content.endText();

                    content.drawLine(30, 440, 600, 440);

                    content.beginText();
                    content.moveTextPositionByAmount(70, 430);
                    content.showText("N Folio");
                    content.newLineAtOffset(70, 0);
                    content.showText("Fecha");
                    content.newLineAtOffset(70, 0);
                    content.showText("Das emisin");
                    content.newLineAtOffset(80, 0);
                    content.showText("Total factura");
                    content.newLineAtOffset(80, 0);
                    content.showText("Monto abono");
                    content.newLineAtOffset(80, 0);
                    content.showText("Saldo deuda");
                    content.newLineAtOffset(80, 0);
                    content.endText();

                    content.drawLine(30, 425, 600, 425);

                    content.beginText();
                    content.moveTextPositionByAmount(75, 390);
                    for (int row : rows) {
                        String folio = tabla.getValueAt(row, 0).toString();
                        String fecha = tabla.getValueAt(row, 3).toString();
                        String dias = tabla.getValueAt(row, 4).toString();
                        int monto = Integer.parseInt(tabla.getValueAt(row, 7).toString());
                        int abono = Integer.parseInt(tabla.getValueAt(row, 11).toString());
                        int saldo = Integer.parseInt(tabla.getValueAt(row, 12).toString());
                        total += saldo;

                        content.showText(folio);
                        content.newLineAtOffset(60, 0);
                        content.showText(fecha);
                        content.newLineAtOffset(90, 0);
                        content.showText(dias);
                        content.newLineAtOffset(70, 0);
                        content.showText(FORMAT.format(monto));
                        content.newLineAtOffset(80, 0);
                        content.showText(FORMAT.format(abono));
                        content.newLineAtOffset(80, 0);
                        content.showText(FORMAT.format(saldo));
                        content.newLineAtOffset(-380, -15);
                    }

                    content.newLineAtOffset(310, -45);
                    content.showText("Total deuda");
                    content.newLineAtOffset(70, 0);
                    content.showText(FORMAT.format(total));
                    content.endText();

                    content.close();
                    doc.save(fileName); // saving as pdf file with name perm 
                    doc.close(); // cleaning memory 

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

                JOptionPane.showMessageDialog(null, "Informe de cobranza generado con xito",
                        "Operacin exitosa", JOptionPane.INFORMATION_MESSAGE);
                //                    liquidaciones.limpiarRemuneraciones();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    //runnable.run();
    runnable.start();
    return true;
}

From source file:controldeadministradores.Admin.java

public void crearPDF(String file, String body) throws Exception {
    String outputFileName = file + ".pdf";
    //        if (args.length > 0)
    //            outputFileName = args[0];

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    // PDPage.PAGE_SIZE_LETTER is also possible
    PDRectangle rect = page1.getMediaBox();
    // rect can be used to get the page width and height
    document.addPage(page1);//  w  w  w .  j  a v  a2 s.  c o m

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE;
    PDFont fontMono = PDType1Font.COURIER;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    int line = 0;

    // Define a text content stream using the selected font, move the cursor and draw some text
    cos.beginText();
    cos.setFont(fontPlain, 14);
    cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line));
    cos.drawString("Reporte de " + file);
    cos.endText();

    String[] txtLine = body.split("-");
    for (int k = 0; k < txtLine.length; k++) {
        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line));
        cos.drawString(txtLine[k]);
        cos.endText();
        cos.close();
    }

    // Make sure that the content stream is closed:

    // Save the results and ensure that the document is properly closed:
    document.save(outputFileName);
    document.close();
}