List of usage examples for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream
public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent, boolean compress, boolean resetContext) throws IOException
From source file:com.fileOperations.EmailBodyToPDF.java
/** * Places the text of the email into the PDF * * @param eml EmailBodyPDF//from w w w . j a v a2 s.c o m */ private static void createEmailBody(EmailBodyPDF eml) { PDDocument doc = null; PDPageContentStream contentStream = null; //Fonts used PDFont bodyTitleFont = PDType1Font.TIMES_BOLD; PDFont bodyFont = PDType1Font.TIMES_ROMAN; //Font Sizes float emailHeaderFontSize = 7; float leadingEmailHeader = 1.5f * emailHeaderFontSize; float bodyFontSize = 12; float leadingBody = 1.5f * bodyFontSize; try { //Create Document, Page, Margins. doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); PDRectangle mediabox = page.getMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; float textYlocation = margin; //Set Line Breaks List<String> sentDateContent = PDFBoxTools.setLineBreaks(eml.getSentDate(), width, emailHeaderFontSize, bodyFont); List<String> recievedDateContent = PDFBoxTools.setLineBreaks(eml.getReceiveDate(), width, emailHeaderFontSize, bodyFont); List<String> toContent = PDFBoxTools.setLineBreaks(eml.getTo(), width, emailHeaderFontSize, bodyFont); List<String> fromContent = PDFBoxTools.setLineBreaks(eml.getFrom(), width, emailHeaderFontSize, bodyFont); List<String> ccContent = PDFBoxTools.setLineBreaks(eml.getCc(), width, emailHeaderFontSize, bodyFont); List<String> bccContent = PDFBoxTools.setLineBreaks(eml.getBcc(), width, emailHeaderFontSize, bodyFont); List<String> attachmentContent = PDFBoxTools.setLineBreaks(eml.getAttachments(), width, emailHeaderFontSize, bodyFont); List<String> subjectContent = PDFBoxTools.setLineBreaks(eml.getSubject(), width, bodyFontSize, bodyFont); List<String> bodyContent = PDFBoxTools.setLineBreaks(eml.getBody(), width, bodyFontSize, bodyFont); //Set Email Header contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); //Set Date Sent if (!"".equals(eml.getSentDate())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("Date Sent: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : sentDateContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set Date Received if (!"".equals(eml.getReceiveDate().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("Date Received: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : recievedDateContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingBody; } } contentStream.newLineAtOffset(0, -leadingBody); //Set From if (!"".equals(eml.getFrom().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("From: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : fromContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set To if (!"".equals(eml.getTo().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("To: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : toContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set CC if (!"".equals(eml.getCc().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("CC: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : ccContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set BCC if (!"".equals(eml.getBcc().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("BCC: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : bccContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set AttachmentList if (!"".equals(eml.getAttachments().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("Attachments: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : attachmentContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set Subject if (!"".equals(eml.getSubject().trim())) { contentStream.newLineAtOffset(0, -leadingBody); contentStream.newLineAtOffset(0, -leadingBody); contentStream.setFont(bodyTitleFont, bodyFontSize); contentStream.showText("Subject: "); contentStream.newLineAtOffset(0, -leadingBody); textYlocation += leadingBody; contentStream.setFont(bodyFont, bodyFontSize); for (String line : subjectContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingBody); textYlocation += leadingBody; } } if (!"".equals(eml.getBody().trim())) { // Set Email Body contentStream.newLineAtOffset(0, -leadingBody); contentStream.setFont(bodyTitleFont, bodyFontSize); contentStream.showText("Message: "); contentStream.setFont(bodyFont, bodyFontSize); contentStream.newLineAtOffset(0, -leadingBody); for (String line : bodyContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, bodyFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } textYlocation += leadingBody; contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingBody); } contentStream.endText(); } contentStream.close(); doc.save(eml.getFilePath() + eml.getFileName()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.fileOperations.StampPDF.java
/** * This stamps docketed files./*w ww . j a v a2s. c om*/ * * @param file String (full file path) * @param docketTime Timestamp * @param dept */ public static void stampDocument(String file, Timestamp docketTime, String dept) { // the document PDDocument doc = null; try { PDFont stampFont = PDType1Font.TIMES_ROMAN; float stampFontSize = 14; String title = PDFBoxTools.HeaderTimeStamp(docketTime) + " " + dept; float titleWidth = stampFont.getStringWidth(title) / 1000 * stampFontSize; float titleHeight = stampFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * stampFontSize; int marginTop = 20; doc = PDDocument.load(new File(file)); if (!doc.isEncrypted()) { for (int i = 0; i < doc.getPages().getCount(); i++) { PDPageContentStream contentStream = null; PDPage page = (PDPage) doc.getPages().get(i); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true); page.getResources().getFontNames(); contentStream.beginText(); contentStream.setFont(stampFont, stampFontSize); contentStream.setNonStrokingColor(Color.RED); contentStream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight); contentStream.showText(title); contentStream.endText(); contentStream.close(); } doc.save(file); } } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.fileOperations.TXTtoPDF.java
/** * Takes the text from the string and insert it into the PDF file * * @param pdfFile String (path + filename) * @param text String (text from document) *//* w w w. j a v a2s . c o m*/ private static void makePDF(String pdfFile, String text) { PDDocument doc = null; PDPageContentStream contentStream = null; //Fonts used PDFont bodyFont = PDType1Font.TIMES_ROMAN; //Font Sizes float bodyFontSize = 12; float leadingBody = 1.5f * bodyFontSize; try { //Create Document, Page, Margins. doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); PDRectangle mediabox = page.getMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; float textYlocation = margin; //Set Line Breaks text = text.replaceAll("[\\p{C}\\p{Z}]", System.getProperty("line.separator")); //strip ZERO WIDTH SPACE List<String> textContent = PDFBoxTools.setLineBreaks(text, width, bodyFontSize, bodyFont); contentStream.beginText(); contentStream.setFont(bodyFont, bodyFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); if (!"".equals(text)) { for (String line : textContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, true, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, bodyFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } textYlocation += leadingBody; contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingBody); } contentStream.endText(); } contentStream.close(); doc.save(pdfFile); } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:es.rickyepoderi.pdfimages.Converter.java
License:Open Source License
/** * Method that converts the images provides to pdf and writes to the target * path specified.// w ww. j a v a 2s .co m * * @param output The file to write * @param bimages The buffered images to put in the pdf * @throws IOException Some error generating the PDF */ public void images2Pdf(File output, File... files) throws IOException { try (PDDocument pdDocument = new PDDocument()) { for (File file : files) { PDPage page = new PDPage(); pdDocument.addPage(page); try (PDPageContentStream pageStream = new PDPageContentStream(pdDocument, page, PDPageContentStream.AppendMode.APPEND, true, true)) { BufferedImage bimage = ImageIO.read(file); PDImageXObject img = LosslessFactory.createFromImage(pdDocument, bimage); Dimension scaledDim = getScaledDimension(new Dimension(img.getWidth(), img.getHeight()), new Dimension((int) page.getMediaBox().getWidth(), (int) page.getMediaBox().getHeight())); pageStream.drawImage(img, 0, 0, scaledDim.width, scaledDim.height); } } pdDocument.save(output); } }
From source file:fys.StatistiekenController.java
@FXML private void handleExportToPDFAction(ActionEvent event) throws IOException { if ((dateFrom.getText() == null || dateFrom.getText().trim().isEmpty()) || (dateTo.getText() == null || dateTo.getText().trim().isEmpty())) { ErrorLabel.setText(taal[93]);//from www .j av a 2s. c om ErrorLabel.setVisible(true); } else { String dateFromInput = dateFrom.getText(); String dateToInput = dateTo.getText(); //Doe dit alleen wanneer er waardes zijn ingevuld. lineChart.setAnimated(false); pieChart.setAnimated(false); //PIECHART //Maak alle data en aantallen weer leeg. int luggage = 0, foundAmount = 0, lostAmount = 0, destroyAmount = 0, settleAmount = 0, neverFoundAmount = 0, depotAmount = 0; int jan = 0, feb = 0, mar = 0, apr = 0, mei = 0, jun = 0, jul = 0, aug = 0, sep = 0, okt = 0, nov = 0, dec = 0; total = 0; series.getData().clear(); pieChartData = FXCollections.observableArrayList(); //Krijg alle data voor de pietchart die tussen de periode van DateFrom en DateTo ligt. try { conn = fys.connectToDatabase(conn); stmt = conn.createStatement(); //connectToDatabase(conn, stmt, "test", "root", "root"); String sql = "SELECT status, date, COUNT(status) AS Count FROM bagagedatabase.luggage_status " + "WHERE date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" " + "AND date <= \"" + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY status"; //Voeg alle aantallen per status toe aan variabelen. try (ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { luggage++; //Retrieve by column name foundAmount = (rs.getInt("status") == 0 ? rs.getInt("Count") : foundAmount); lostAmount = (rs.getInt("status") == 1 ? rs.getInt("Count") : lostAmount); destroyAmount = (rs.getInt("status") == 2 ? rs.getInt("Count") : destroyAmount); settleAmount = (rs.getInt("status") == 3 ? rs.getInt("Count") : settleAmount); neverFoundAmount = (rs.getInt("status") == 4 ? rs.getInt("Count") : neverFoundAmount); depotAmount = (rs.getInt("status") == 5 ? rs.getInt("Count") : depotAmount); } } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } //Voeg de waardes toe aan de array. pieChartData = FXCollections.observableArrayList(new PieChart.Data(ExportToPdfTexts[15], foundAmount), new PieChart.Data(ExportToPdfTexts[16], lostAmount), new PieChart.Data(ExportToPdfTexts[17], destroyAmount), new PieChart.Data(ExportToPdfTexts[18], settleAmount), new PieChart.Data(ExportToPdfTexts[19], neverFoundAmount), new PieChart.Data(ExportToPdfTexts[20], depotAmount)); //Update de titel pieChart.setTitle(ExportToPdfTexts[0]); //Update de piechart met de gevraagde gegevens. pieChart.setData(pieChartData); //Voor elke aantal tel ze met elkaar op en sla het op bij total. for (PieChart.Data d : pieChart.getData()) { total += d.getPieValue(); } //Verander de tekst van elke piechartdata. naar: (aantal statusnaam: percentage). pieChartData.forEach(data -> data.nameProperty().bind(Bindings.concat((int) data.getPieValue(), " ", data.getName(), ": ", (total == 0 || (int) data.getPieValue() == 0) ? 0 : (int) (data.getPieValue() / total * 100), "%"))); //LINECHART //Krijg alle data voor de linechart die tussen de periode van DateFrom en DateTo ligt. try { conn = fys.connectToDatabase(conn); stmt = conn.createStatement(); String sql = "SELECT date, COUNT(date) as Count FROM bagagedatabase.luggage_status " + "WHERE status = 6 AND date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" " + "AND date <= \"" + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY date"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { //Retrieve by column name //Voeg alle aantallen per maand toe aan variabelen. if (rs.getString("date") != null) { //Krijg van elke date record de maand eruit. String str[] = rs.getString("date").split("-"); int month = Integer.parseInt(str[1]); jan = (month == 1 ? jan += rs.getInt("Count") : jan); feb = (month == 2 ? feb += rs.getInt("Count") : feb); mar = (month == 3 ? mar += rs.getInt("Count") : mar); apr = (month == 4 ? apr += rs.getInt("Count") : apr); mei = (month == 5 ? jan += rs.getInt("Count") : mei); jun = (month == 6 ? jun += rs.getInt("Count") : jun); jul = (month == 7 ? jul += rs.getInt("Count") : jul); aug = (month == 8 ? aug += rs.getInt("Count") : aug); sep = (month == 9 ? sep += rs.getInt("Count") : sep); okt = (month == 10 ? okt += rs.getInt("Count") : okt); nov = (month == 11 ? nov += rs.getInt("Count") : nov); dec = (month == 12 ? dec += rs.getInt("Count") : dec); } } rs.close(); conn.close(); } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } //Update de titel lineChart.setTitle(ExportToPdfTexts[1]); //Update de linechart naar de waardes die gewenst is. series.setName(ExportToPdfTexts[2]); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[3], jan)); series.getData().add(new XYChart.Data(ExportToPdfTexts[4], feb)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[5], mar)); series.getData().add(new XYChart.Data(ExportToPdfTexts[6], apr)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[7], mei)); series.getData().add(new XYChart.Data(ExportToPdfTexts[8], jun)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[9], jul)); series.getData().add(new XYChart.Data(ExportToPdfTexts[10], aug)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[11], sep)); series.getData().add(new XYChart.Data(ExportToPdfTexts[12], okt)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[13], nov)); series.getData().add(new XYChart.Data(ExportToPdfTexts[14], dec)); //Update de piechart en linechart voordat er een screenshot van genomen wordt. lineChart.applyCss(); lineChart.layout(); pieChart.applyCss(); pieChart.layout(); //Maak een screenshot van de piechart en linechart. savePieChartAsPng(); saveLineChartAsPng(); try { //Krijg de datum van vandaag voor pdf. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String dateString = dateFormat.format(date); //Krijg de content van de template pdf en maake nieuw pdf aan. File pdfdoc = new File("src/fys/templates/statisticstemplate.pdf"); PDDocument document = null; document = PDDocument.load(pdfdoc); PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); List<PDField> fields = acroForm.getFields(); // set the text in the form-field <-- does work //Verander voor elk veld de waardes. for (PDField field : fields) { if (field.getFullyQualifiedName().equals("found")) { field.setValue(String.valueOf(foundAmount)); } if (field.getFullyQualifiedName().equals("lost")) { field.setValue(String.valueOf(lostAmount)); } if (field.getFullyQualifiedName().equals("destroyed")) { field.setValue(String.valueOf(destroyAmount)); } if (field.getFullyQualifiedName().equals("completed")) { field.setValue(String.valueOf(settleAmount)); } if (field.getFullyQualifiedName().equals("neverfound")) { field.setValue(String.valueOf(neverFoundAmount)); } if (field.getFullyQualifiedName().equals("depot")) { field.setValue(String.valueOf(depotAmount)); } if (field.getFullyQualifiedName().equals("jan")) { field.setValue(String.valueOf(jan)); } if (field.getFullyQualifiedName().equals("feb")) { field.setValue(String.valueOf(feb)); } if (field.getFullyQualifiedName().equals("mar")) { field.setValue(String.valueOf(mar)); } if (field.getFullyQualifiedName().equals("apr")) { field.setValue(String.valueOf(apr)); } if (field.getFullyQualifiedName().equals("may")) { field.setValue(String.valueOf(mei)); } if (field.getFullyQualifiedName().equals("jun")) { field.setValue(String.valueOf(jun)); } if (field.getFullyQualifiedName().equals("jul")) { field.setValue(String.valueOf(jul)); } if (field.getFullyQualifiedName().equals("aug")) { field.setValue(String.valueOf(aug)); } if (field.getFullyQualifiedName().equals("sep")) { field.setValue(String.valueOf(sep)); } if (field.getFullyQualifiedName().equals("oct")) { field.setValue(String.valueOf(okt)); } if (field.getFullyQualifiedName().equals("nov")) { field.setValue(String.valueOf(nov)); } if (field.getFullyQualifiedName().equals("dec")) { field.setValue(String.valueOf(dec)); } if (field.getFullyQualifiedName().equals("date")) { field.setValue(String.valueOf(dateString)); } if (field.getFullyQualifiedName().equals("period")) { field.setValue(String.valueOf(dateFromInput + " | " + dateToInput)); } } //Retrieving the page PDPage page = document.getPage(0); //Creating PDImageXObject object loginController login = new loginController(); PDImageXObject pieChartImage = PDImageXObject .createFromFile("src/fys/statistieken/PieChart_" + login.getUsersName() + ".png", document); PDImageXObject lineChartImage = PDImageXObject.createFromFile( "src/fys/statistieken/LineChart_" + login.getUsersName() + ".png", document); //creating the PDPageContentStream object PDPageContentStream contents = new PDPageContentStream(document, page, true, true, true); //Drawing the image in the PDF document contents.drawImage(pieChartImage, 75, 0, 350, 300); contents.drawImage(lineChartImage, 425, 0, 350, 300); //Closing the PDPageContentStream object contents.close(); //Sla het docment op. document.save("src/fys/statistieken/statistics" + dateFromInput + dateToInput + ".pdf"); document.close(); //Verwijder de plaatjes die waren opgeslagen. savePieChartAsPng().delete(); saveLineChartAsPng().delete(); //Sluit de popup home_pane.setDisable(false); pdfPane.setVisible(false); } catch (IOException ex) { Logger.getLogger(StatistiekenController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:net.bookinaction.ExtractAnnotations.java
License:Apache License
public void doJob(String job, Float[] pA) throws IOException { PDDocument document = null;/*from w ww . ja v a 2 s . c o m*/ Stamper s = new Stamper(); // utility class final String job_file = job + ".pdf"; final String dic_file = job + "-dict.txt"; final String new_job = job + "-new.pdf"; PrintWriter writer = new PrintWriter(dic_file); ImageLocationListener imageLocationsListener = new ImageLocationListener(); AnnotationMaker annotMaker = new AnnotationMaker(); try { document = PDDocument.load(new File(job_file)); int pageNum = 0; for (PDPage page : document.getPages()) { pageNum++; PDRectangle cropBox = page.getCropBox(); List<PDAnnotation> annotations = page.getAnnotations(); // extract image locations List<Rectangle2D> imageRects = new ArrayList<Rectangle2D>(); imageLocationsListener.setImageRects(imageRects); imageLocationsListener.processPage(page); int im = 0; for (Rectangle2D pdImageRect : imageRects) { s.recordImage(writer, pageNum, "[im" + im + "]", (Rectangle2D.Float) pdImageRect); annotations.add(annotMaker.squareAnnotation(Color.YELLOW, (Rectangle2D.Float) pdImageRect, "[im" + im + "]")); im++; } PDFTextStripperByArea stripper = new PDFTextStripperByArea(); int j = 0; List<PDAnnotation> viableAnnots = new ArrayList(); for (PDAnnotation annot : annotations) { if (annot instanceof PDAnnotationTextMarkup || annot instanceof PDAnnotationLink) { stripper.addRegion(Integer.toString(j++), s.getAwtRect( s.adjustedRect(annot.getRectangle(), pA[0], pA[1], pA[2], pA[3]), cropBox)); viableAnnots.add(annot); } else if (annot instanceof PDAnnotationPopup || annot instanceof PDAnnotationText) { viableAnnots.add(annot); } } stripper.extractRegions(page); List<PDRectangle> rects = new ArrayList<PDRectangle>(); List<String> comments = new ArrayList<String>(); List<String> highlightTexts = new ArrayList<String>(); j = 0; for (PDAnnotation viableAnnot : viableAnnots) { if (viableAnnot instanceof PDAnnotationTextMarkup) { String highlightText = stripper.getTextForRegion(Integer.toString(j++)); String withoutCR = highlightText.replace((char) 0x0A, '^'); String comment = viableAnnot.getContents(); String colorString = String.format("%06x", viableAnnot.getColor().toRGB()); PDRectangle aRect = s.adjustedRect(viableAnnot.getRectangle(), pA[4], pA[5], pA[6], pA[7]); rects.add(aRect); comments.add(comment); highlightTexts.add(highlightText); s.recordTextMarkup(writer, pageNum, comment, withoutCR, aRect, colorString); } else if (viableAnnot instanceof PDAnnotationText) { String comment = viableAnnot.getContents(); String colorString = String.format("%06x", viableAnnot.getColor().toRGB()); for (Rectangle2D pdImageRect : imageRects) { if (pdImageRect.contains(viableAnnot.getRectangle().getLowerLeftX(), viableAnnot.getRectangle().getLowerLeftY())) { s.recordTextMarkup(writer, pageNum, comment, "", (Rectangle2D.Float) pdImageRect, colorString); annotations.add(annotMaker.squareAnnotation(Color.GREEN, (Rectangle2D.Float) pdImageRect, comment)); } ; } } } PDPageContentStream canvas = new PDPageContentStream(document, page, true, true, true); int i = 0; for (PDRectangle pdRect : rects) { String comment = comments.get(i); String highlightText = highlightTexts.get(i); //annotations.add(linkAnnotation(pdRect, comment, highlightText)); //annotations.add(annotationSquareCircle(pdRect, BLUE)); s.showBox(canvas, new Rectangle2D.Float(pdRect.getLowerLeftX(), pdRect.getUpperRightY(), pdRect.getWidth(), pdRect.getHeight()), cropBox, Color.BLUE); i++; } canvas.close(); } writer.close(); document.save(new_job); } finally { if (document != null) { document.close(); } } }
From source file:net.bookinaction.TextInfoExtractor.java
License:Apache License
public static void getTextPositionFromPage(PDDocument document, StripperParam stripperParam, int pageNum, PrintWriter writer, boolean testMode) throws IOException { //System.out.println(String.format("getPage: %d", pageNum)); PDPage page = document.getPage(pageNum - 1); // pdfbox uses the 0-base index PDRectangle cropBox = page.getCropBox(); // extract image locations ImageLocationListener imageLocationsListener = new ImageLocationListener(); List<Rectangle2D> imageRects = new ArrayList<Rectangle2D>(); imageLocationsListener.setImageRects(imageRects); imageLocationsListener.processPage(page); // extract Text locations StripString stripString = new StripString(); TextLocationListener stripper = new TextLocationListener(stripperParam, stripString); stripper.setSortByPosition(true);/*from w w w . j ava2 s . c o m*/ List<StripLine> stripLines = new ArrayList<StripLine>(); stripper.setStartPage(pageNum); stripper.setEndPage(pageNum); try { stripper.writeText(document, new OutputStreamWriter(new ByteArrayOutputStream())); } catch (IOException e) { return; } if (page.getContents() != null) stripper.processPage(page); // declare canvas and keep this position PDPageContentStream canvas = new PDPageContentStream(document, page, true, true, true); Stamper s = new Stamper(); // utility class if (testMode) { // draw the bounding box of each character for (int i = 0; i < stripString.size(); i++) { // original Rectangle s.showBox(canvas, stripString.boundingRect(i), cropBox, Color.GRAY80); } } s.recordPageSize(writer, pageNum, cropBox); // splits into lines int lineNum = 1; int lineStart = 0, lineEnd = 0; String[] splits = stripString.toString().split("\r"); SimpleTokenizer simpleTokenizer = new SimpleTokenizer(); for (String lineText : splits) { if (lineText.length() < 1) continue; lineEnd = lineStart + lineText.length(); Rectangle2D mergedRect = stripString.boundingRect(lineStart, lineEnd - 1); String sub = stripString.substring(lineStart, lineEnd); stripLines.add(new StripLine(pageNum, lineNum, lineStart, lineEnd, mergedRect)); //System.out.println(String.format("%d-%d: %s - [%.0f %.0f %.0f %.0f]", pageNum, lineNum, sub, // mergedRect.getX(), mergedRect.getY(), mergedRect.getWidth(), mergedRect.getHeight())); if (testMode) { s.showBox(canvas, mergedRect, cropBox, Color.GREEN); } s.recordTextPosition(writer, sub, pageNum, mergedRect, "LINE"); /******* get words in the line *********/ List<Token> tokens = simpleTokenizer.getTokens(sub); for (String pattern : circles_patterns) { List<Token> symbolTokens = PatternAnalyzer.getTokensByPattern(sub, pattern); tokens.addAll(symbolTokens); } for (Token t : tokens) { mergedRect = stripString.boundingRect(lineStart + t.getStart(), lineStart + t.getEnd() - 1); //System.out.println(String.format("%d-%d: %s - [%.0f %.0f %.0f %.0f]", pageNum, lineNum, t.getStem(), mergedRect.getX(), mergedRect.getY(), mergedRect.getWidth(), mergedRect.getHeight())); s.recordTextPosition(writer, t.getStem(), pageNum, mergedRect, "TEXT"); if (testMode) { s.showBox(canvas, mergedRect, cropBox, Color.RED); } } lineStart += lineText.length() + 1; lineNum++; } // ------------------- // markup textMark annotation to the image int imageNum = 1; for (Rectangle2D imRect : imageRects) { //page.getAnnotations().add(annotationMaker.textMarkupAnnotation(Color.YELLOW, (Rectangle2D.Float) imRect, "image"+imageNum)); if (testMode) { s.showBox(canvas, imRect, cropBox, Color.YELLOW); } s.recordTextPosition(writer, "[image" + imageNum + "]", pageNum, imRect, "IMAGE"); imageNum++; } canvas.close(); }
From source file:org.esteco.jira.pdf.AddImageToPDF.java
License:Apache License
/** * Add an image to an existing PDF document. * * @param inputFile The input PDF to add the image to. * @param imagePath The filename of the image to put in the PDF. * @param outputFile The file to write to the pdf to. * @throws IOException If there is an error writing the data. *//* w w w .j a v a 2s . c om*/ public void createPDFFromImage(String inputFile, String imagePath, String outputFile) throws IOException { // the document PDDocument doc = null; try { doc = PDDocument.load(new File(inputFile)); //we will add the image to the first page. PDPage page = doc.getPage(0); //page.setRotation(90); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 0.4f; contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale); contentStream.close(); doc.save(outputFile); } finally { if (doc != null) { doc.close(); } } }
From source file:org.gfbio.idmg.util.PDFUtil.java
private void printFooter() throws IOException { //Set contentStream new for footer content = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true); content.beginText();//w w w . j av a 2 s . c om // Print Footer content.newLineAtOffset(70, 25); content.setNonStrokingColor(Color.GRAY); content.setFont(PDType1Font.HELVETICA, 8); String footer = "This data management plan was computer-produced by GFBio DMP-Tool. For revision and support please contact info@gfbio.org."; content.showText(footer); content.endText(); // Closing the content stream content.close(); }
From source file:pdf.merge.application.BLL.PDFWriter.java
public PDFWriter(File file, String filePath, Boolean headerActivated, Boolean footerActivated, String headerContent, String footerContent) { try {//from w ww . j ava 2 s . c om // rcupration du fichier modifier document = PDDocument.load(file); // rcupration de l'ensemble des pages du PDF gnr en amont allPages = document.getDocumentCatalog().getPages(); // on boucle sur le nombre de pages du PDF for (int i = 0; i < allPages.getCount(); i++) { // on rcupre la premire page page = (PDPage) allPages.get(i); contentStream = new PDPageContentStream(document, page, true, true, true); // dbut de l'criture contentStream.beginText(); contentStream.setFont(font, fontSize); // si le header doit tre crit, ou le footer ou les deux if (headerActivated && footerActivated) { // on se positionne sur le PDF contentStream.moveTextPositionByAmount(5, 580); // on crit sur le contenu enregistr pour le header contentStream.drawString(headerContent); contentStream.moveTextPositionByAmount(5, -550); contentStream.drawString(footerContent); } else if (headerActivated) { contentStream.moveTextPositionByAmount(5, 580); contentStream.drawString(headerContent); } else { contentStream.moveTextPositionByAmount(5, -550); contentStream.drawString(footerContent); } // fin du processus d'criture + fermeture contentStream.endText(); contentStream.close(); } // on crase le fichier enregistr prcdemment document.save(filePath); } catch (IOException e) { System.out.println("Erreur : " + e.getMessage()); } }