List of usage examples for org.apache.pdfbox.pdmodel PDDocument PDDocument
public PDDocument()
From source file:Clavis.Windows.WShedule.java
public void createPDFDocument(String nome, String[][] valores) { PDDocument doc = new PDDocument(); try {// w w w.j a v a2s .c om String titulo = lingua.translate("Registo de emprstimos / requisies do recurso") + ": " + lingua.translate(mat.getTypeOfMaterialName()) + " " + lingua.translate(mat.getDescription()); String subtitulo = lingua.translate("Desde") + ": " + inicio.toString() + " " + lingua.translate("at") + ": " + fim.toString(); String subsubtitulo = lingua.translate("Estado") + ": " + lingua.translate(estado); drawTable(doc, valores, titulo, subtitulo, subsubtitulo); doc.save(nome); doc.close(); } catch (IOException ex) { Logger.getLogger(WShedule.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.baseprogramming.pdwriter.PdWriterTest.java
License:Apache License
@Test public void testWriteTable() { List<Map<String, Object>> data = getDataTable(50); final File file = new File("C:/tmp/test-PdWriter-PdTable.pdf"); Margin margin = new Margin(0.75f, 0.2f, 0.5f, 0.5f); try (PDDocument doc = new PDDocument()) { PdWriter writer = new PdWriter(doc, margin); PdTable table = writer.createTable("First Name", "Middle Name", "Last Name", "D.O.B", "Memo"); Borders border = new Borders(3, 1, 2, 1); table.setCellPadding(new PdPoints(10)); table.setRowBorder(1);/* w w w .j av a2s.com*/ table.setColumnBorder(1); table.setBorder(border); PdTableHeader header = table.getHeader(); header.setFont(PDType1Font.TIMES_BOLD); table.calculateColumnWidths(data, 5); PdColumn memo = header.getColumn("Memo"); memo.setWidth(new PdInch(2)); for (PdColumn column : header.getColumns()) { System.out.printf("%s->%s\n", column.getName(), column.getWidth()); } writer.write(table, data); doc.save(file); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.baseprogramming.pdwriter.PdWriterTest.java
License:Apache License
@Test public void testHtmlWriter() { File input = new File("c:/tmp/html-input-simple.html"); File output = new File("c:/tmp/html-input-simple.pdf"); Margin margin = new Margin(0.75f, 0.2f, 0.5f, 0.5f); try (PDDocument pdDoc = new PDDocument()) { PdWriter writer = new PdWriter(pdDoc, margin); writer.writeHtml(input);//from ww w . ja v a 2s . c om pdDoc.save(output); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.baseprogramming.pdwriter.PdWriterTest.java
License:Apache License
@Test public void testBasicDemo() { try (PDDocument pdDoc = new PDDocument()) { Margin margin = new Margin(0.75f, 0.2f, 0.5f, 0.25f); PdWriter writer = new PdWriter(pdDoc, margin); PdParagraph title = writer.createParagraph(); title.setFont(PDType1Font.TIMES_BOLD); title.setFontSize(24);/*from w w w . j av a 2s . c o m*/ title.setAboveSpacing(new PdInch(0.75f)); title.setBelowSpacing(new PdInch(0.75f)); PdParagraph heading = writer.createParagraph(); heading.setFont(PDType1Font.TIMES_BOLD_ITALIC); heading.setFontSize(16); heading.setAboveSpacing(new PdInch(0.1f)); PdParagraph body = writer.createParagraph(); body.setBelowSpacing(new PdInch(0.17f)); PdParagraph code = writer.createParagraph(); code.setFont(PDType1Font.COURIER); code.setBeforeTextIndent(new PdInch(0.5f)); code.setAboveSpacing(new PdInch(0.1f)); code.setBelowSpacing(new PdInch(0.1f)); writer.write(title, "PdWriter Class"); writeBasicParagraphDemo(writer, body, code, heading); writeListDemo(writer, body, code, heading); writeTableDemo(writer, heading, body, code); writeImageDemo(writer, heading, body, code); writeHtmlDemo(writer, heading, body, code); pdDoc.save(new File("c:/tmp/PdWriter-Demo.pdf")); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.baseprogramming.pdwriter.PdWriterTest.java
License:Apache License
@Test public void testTextFileToPdf() { String fileName = "sample-text-file"; String path = "c:/tmp/" + fileName + ".txt"; File output = new File("c:/tmp/" + fileName + ".pdf"); Margin margin = new Margin(0.75f, 0.2f, 0.5f, 0.25f); try (PDDocument pdDoc = new PDDocument()) { int parSize = 30; int parCount = 100; generateTextFile(new File(path), 30, 100); PdWriter writer = new PdWriter(pdDoc, margin); String string = String.format( "This is a PDF file created from a randomly generated text file. The text file has %s paragraph(s), each with %s randomly genrated words. This example demonstrates how text is wrapped when the margin is reached (you will not from the text file that each paragraph appears as a single line of text), as well a new page started when the end of the page is reached. ", parCount, parSize);/*from w ww .j a v a 2 s.c o m*/ PdParagraph intro = writer.createParagraph(); intro.setFont(PDType1Font.COURIER_OBLIQUE); intro.setAboveSpacing(new PdInch(0.17f)); intro.setBelowSpacing(new PdInch(0.5f)); writer.write(intro, string); PdParagraph par = writer.createParagraph(); for (String line : Files.readAllLines(Paths.get(path))) { writer.write(par, line); } pdDoc.save(output); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.baseprogramming.pdwriter.PdWriterTest.java
License:Apache License
@Test public void testMarkdownTests() { try (PDDocument doc = new PDDocument()) { Margin margin = new Margin(1.0f); PdWriter writer = new PdWriter(doc, margin); String html = Processor.process( "Testing **markdown**. Note how the word 'markdown' was converted. How about a word _enclosed_ in underscores?. Is that underlined? #what is this? "); writer.writeHtml(html);//w ww. ja v a2s.com System.out.println(Processor.process("#Extra Extra.")); writer.writeHtml(Processor.process("#Extra Extra.")); writer.writeHtml(Processor.process("##Not as important")); writer.writeHtml(Processor.process("###Even less important")); writer.writeHtml(Processor.process("####Hardly worth mentioning")); html = Processor.process("This is a plain paragraph"); System.out.println(html); writer.writeHtml(html); html = Processor.process( ">I am not sure blockquotes have a scanner/handler. However, adding a **blockquote** selector in the file --default-css.css-- can set the styles required."); writer.writeHtml(html); System.out.println(html); doc.save("c:/tmp/markdown-tests.pdf"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.devnexus.ting.web.controller.PdfUtils.java
License:Apache License
public PdfUtils(float margin, String title) throws IOException { this.margin = margin; doc = new PDDocument(); baseFont = PDType0Font.load(doc, PdfUtils.class.getResourceAsStream("/fonts/Arial.ttf")); headerFont = PDType1Font.HELVETICA_BOLD; subHeaderFont = PDType1Font.HELVETICA_BOLD; devnexusLogo = PDDocument.load(PdfUtils.class.getResourceAsStream("/fonts/devnexus-logo.pdf")); this.currentPage = new PDPage(); this.pages.add(currentPage); this.doc.addPage(currentPage); final PDRectangle mediabox = currentPage.getMediaBox(); this.width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; this.initialHeightCounter = startY; this.heightCounter = startY; LOGGER.info(String.format(// w ww . j a v a 2s.com "Margin: %s, width: %s, startX: %s, " + "startY: %s, heightCounter: %s, baseFontSize: %s, headerFontSize: %s", margin, width, startX, startY, heightCounter, baseFont, headerFont)); contents = new PDPageContentStream(doc, currentPage); // Add Logo final LayerUtility layerUtility = new LayerUtility(doc); final PDFormXObject logo = layerUtility.importPageAsForm(devnexusLogo, 0); final AffineTransform affineTransform = AffineTransform.getTranslateInstance(100, startY - 50); affineTransform.scale(2d, 2d); layerUtility.appendFormAsLayer(currentPage, logo, affineTransform, "devnexus-logo"); this.heightCounter -= 100; this.contents.beginText(); this.contents.setFont(headerFont, headerFontSize); this.currentLeading = this.lineSpacing * baseFontSize; this.contents.setLeading(this.currentLeading); contents.newLineAtOffset(50, heightCounter); println(title); this.contents.setFont(baseFont, baseFontSize); this.currentLeading = this.lineSpacing * baseFontSize; this.contents.setLeading(this.currentLeading); println(); }
From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java
License:Open Source License
/** * Prints the current page to a pdf file * * @throws IOException if the file cannot be found or the pdf cannot be created *//*from w w w . j av a 2 s .c om*/ protected void printCurrentPageToPdf() throws IOException { io.clearActivePoints(); ddf.updateAll(io.getActivePoints()); String fileName = DBMenuBar.cleanseFileName( Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6) + ": " + Main.getCurrentPage().toDisplayString().replaceAll("\\|", "-")); File f = new File(Main.getFilePath()); f.mkdirs(); f = new File(Main.getFilePath() + fileName + ".pdf"); BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paintComponent(g); g.dispose(); PDDocument doc = null; try { doc = new PDDocument(); boolean crop = true; State.print(field); for (Point p : Main.getCurrentPage().getDots().keySet()) if (p.getX() < field.getWidth() * 0.1 + field.getX() || p.getX() > field.getWidth() * 0.9 + field.getX()) { crop = false; break; } if (Main.getCurrentPage().getTextPoint().getX() < field.getWidth() * 0.1 + field.getX() || Main.getCurrentPage().getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX()) crop = false; float scale = 1.0f; if (crop) scale = 0.8f; PDPage page = new PDPage(new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight())); doc.addPage(page); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true); contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()), -1 * field.y, pdImage.getWidth(), pdImage.getHeight()); contentStream.close(); doc.save(f); } finally { if (doc != null) doc.close(); } }
From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java
License:Open Source License
/** * Prints every page to a pdf file// www. ja v a 2 s . co m * * @throws IOException if the file cannot be found or the pdf cannot be created */ protected void printAllPagesToPdf() throws IOException { io.clearActivePoints(); ddf.updateAll(io.getActivePoints()); File f = new File(Main.getFilePath()); f.mkdirs(); String fileName = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)); f = new File(Main.getFilePath() + fileName + " full show" + ".pdf"); boolean crop = true; a: for (int pageNum : Main.getPages().keySet()) { for (Point p : Main.getPages().get(pageNum).getDots().keySet()) { if (p.getX() < field.getWidth() * 0.1 + field.getX() || p.getX() > field.getWidth() * 0.9 + field.getX()) { crop = false; break a; } } if (Main.getPages().get(pageNum).getTextPoint().getX() < field.getWidth() * 0.1 + field.getX() || Main.getPages().get(pageNum).getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX()) { crop = false; break; } } float scale = 1.0f; if (crop) scale = 0.8f; PDDocument doc = null; try { doc = new PDDocument(); for (int i : Main.getPages().keySet()) { Main.setCurrentPage(i); BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paintComponent(g); g.dispose(); PDPage page = new PDPage( new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight())); doc.addPage(page); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true); contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()), -1 * field.y, pdImage.getWidth(), pdImage.getHeight()); contentStream.close(); } doc.save(f); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); pdf.updateAfterPrintAll(); } }
From source file:com.evanbelcher.DrillBook.DotSheetMaker.java
License:Open Source License
/** * Prints all dot sheets to pdf files//from ww w . jav a2 s. c om */ private void printAllToPdf() throws IOException { printing = true; String folder = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)) + " Dot Sheets/"; File f = new File(Main.getFilePath() + folder); f.mkdirs(); PDDocument doc = null; String[] chars = new String[26]; for (int i = 0; i < 26; i++) chars[i] = String.valueOf((char) (65 + i)); try { for (String letter : chars) { doc = new PDDocument(); String fileName = Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6) + " " + DBMenuBar.cleanseFileName(letter); f = new File(Main.getFilePath() + folder + fileName + " dot sheet.pdf"); ArrayList<String> list = new ArrayList<>(map.keySet()); list.sort(nameComparator); for (String dotName : list) { if (dotName.replaceAll("[0-9]", "").equals(letter)) { int i = 0; PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.beginText(); contentStream.setFont(font, 10.0f); contentStream.newLineAtOffset(10, page.getMediaBox().getHeight() - 20); contentStream.showText(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.3f, page.getMediaBox().getHeight() - 20); contentStream.showText(dotName); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 10.0f); contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.6f, page.getMediaBox().getHeight() - 20); contentStream.showText("Name: ______________________________"); contentStream.endText(); contentStream.close(); float margin = 10; float tableWidth = page.getMediaBox().getWidth() - (2 * margin); float yStartNewPage = page.getMediaBox().getHeight() - (3 * margin); //noinspection UnnecessaryLocalVariable float yStart = yStartNewPage; float bottomMargin = 70; BaseTable table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); //Create Header row Row<PDPage> headerRow = table.createRow(15f); Cell<PDPage> headerCell = headerRow.createCell(100 / 7f, "Set #"); headerCell.setAlign(HorizontalAlignment.CENTER); headerCell.setFillColor(HEADER_COLOR); headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell); headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell); table.addHeaderRow(headerRow); for (int pageNum : new TreeSet<>(map.get(dotName).keySet())) { String text = map.get(dotName).get(pageNum); String[] lines = text.split("\\n"); String line1 = lines[0].replace("Horizontal - ", ""); String line2 = lines[1].replace("Vertical - ", ""); Row<PDPage> row = table.createRow(10f); Cell<PDPage> cell = row.createCell(100 / 7f, pageNum + ""); cell.setAlign(HorizontalAlignment.CENTER); cell.setFillColor(openingSets.contains(pageNum) ? OPENING_SET_COLOR : NORMAL_COLOR); row.createCell(300 / 7f, line1).copyCellStyle(cell); row.createCell(300 / 7f, line2).copyCellStyle(cell); if (++i >= 35) { table.draw(); page = new PDPage(); doc.addPage(page); table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); //Create Header row headerRow = table.createRow(15f); headerCell = headerRow.createCell(100 / 7f, "Set #"); headerCell.setAlign(HorizontalAlignment.CENTER); headerCell.setFillColor(HEADER_COLOR); headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell); headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell); table.addHeaderRow(headerRow); i -= 35; } } table.draw(); } } if (doc.getNumberOfPages() > 0) doc.save(f); else doc.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); } printing = false; }