Java Examples for org.apache.pdfbox.pdmodel.font.PDType1Font
The following java examples will help you to understand the usage of org.apache.pdfbox.pdmodel.font.PDType1Font. These source code samples are taken from different open source projects.
Example 1
| Project: PdfLayoutManager-master File: TestManualllyPdfLayoutMgr.java View source code |
@Test
public void testPdf() throws IOException, COSVisitorException {
// Nothing happens without a PdfLayoutMgr.
PdfLayoutMgr pageMgr = PdfLayoutMgr.newRgbPageMgr();
// One inch is 72 document units. 40 is about a half-inch - enough margin to satisfy most
// printers. A typical monitor has 72 dots per inch, so you can think of these as pixels
// even though they aren't. Things can be aligned right, center, top, or anywhere within
// a "pixel".
final float pMargin = 40;
// A LogicalPage is a group of pages with the same settings. When your contents scroll off
// the bottom of a page, a new page is automatically created for you with the settings taken
// from the LogicPage grouping. If you don't want a new page, be sure to stay within the
// bounds of the current one!
LogicalPage lp = pageMgr.logicalPageStart();
// Set up some useful constants for later.
final float tableWidth = lp.pageWidth() - (2 * pMargin);
final float pageRMargin = pMargin + tableWidth;
final float colWidth = tableWidth / 4f;
final float[] colWidths = new float[] { colWidth + 10, colWidth + 10, colWidth + 10, colWidth - 30 };
final Padding textCellPadding = Padding.of(2f);
// Set up some useful styles for later
final TextStyle heading = TextStyle.of(PDType1Font.HELVETICA_BOLD, 9.5f, WHITE);
final CellStyle headingCell = CellStyle.of(BOTTOM_CENTER, textCellPadding, BLUE, BorderStyle.builder().left(LineStyle.of(BLUE)).right(LineStyle.of(WHITE)).build());
final CellStyle headingCellR = CellStyle.of(BOTTOM_CENTER, textCellPadding, BLACK, BorderStyle.builder().left(LineStyle.of(WHITE)).right(LineStyle.of(BLACK)).build());
final TextStyle regular = TextStyle.of(PDType1Font.HELVETICA, 9.5f, BLACK);
final CellStyle regularCell = CellStyle.of(TOP_LEFT, textCellPadding, null, BorderStyle.builder().left(LineStyle.of(BLACK)).right(LineStyle.of(BLACK)).bottom(LineStyle.of(BLACK)).build());
// Let's draw three tables on our first landscape-style page grouping.
// Draw the first table with lots of extra room to show off the vertical and horizontal
// alignment.
XyOffset xya = lp.tableBuilder(XyOffset.of(40f, lp.yPageTop())).addCellWidths(vec(120f, 120f, 120f)).textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder().cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK))).rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder().cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY))).minRowHeight(120f).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder().cellBuilder().align(TOP_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder().cellBuilder().align(MIDDLE_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(MIDDLE_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(MIDDLE_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder().cellBuilder().align(BOTTOM_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(BOTTOM_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(BOTTOM_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().buildPart().buildTable();
// The second table uses the x and y offsets from the previous table to position it to the
// right of the first.
XyOffset xyb = lp.tableBuilder(XyOffset.of(xya.x() + 10, lp.yPageTop())).addCellWidths(vec(100f, 100f, 100f)).textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder().cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK))).rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder().cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY))).minRowHeight(100f).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder().cellBuilder().align(BOTTOM_RIGHT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(BOTTOM_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(BOTTOM_LEFT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder().cellBuilder().align(MIDDLE_RIGHT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(MIDDLE_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(MIDDLE_LEFT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder().cellBuilder().align(TOP_RIGHT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_LEFT).add("Line 1", "Line two", "Line three").buildCell().buildRow().buildPart().buildTable();
// The third table uses the x and y offsets from the previous tables to position it to the
// right of the first and below the second. Negative Y is down. This third table showcases
// the way cells extend vertically (but not horizontally) to fit the text you put in them.
lp.tableBuilder(XyOffset.of(xya.x() + 10, xyb.y() - 10)).addCellWidths(vec(100f, 100f, 100f)).textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder().cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK))).rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder().cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY))).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder().cellBuilder().align(BOTTOM_RIGHT).add("Line 1").buildCell().cellBuilder().align(BOTTOM_CENTER).add("Line 1", "Line two").buildCell().cellBuilder().align(BOTTOM_LEFT).add("Line 1", "Line two", "[Line three is long enough to wrap]").buildCell().buildRow().rowBuilder().cellBuilder().align(MIDDLE_RIGHT).add("Line 1", "Line two").buildCell().cellBuilder().align(MIDDLE_CENTER).add("").buildCell().cellBuilder().align(MIDDLE_LEFT).add("Line 1").buildCell().buildRow().rowBuilder().cellBuilder().align(TOP_RIGHT).add("L1").buildCell().cellBuilder().align(TOP_CENTER).add("Line 1", "Line two").buildCell().cellBuilder().align(TOP_LEFT).add("Line 1").buildCell().buildRow().buildPart().buildTable();
lp.commit();
// Let's do a portrait page now. I just copied this from the previous page.
lp = pageMgr.logicalPageStart(LogicalPage.Orientation.PORTRAIT);
lp.tableBuilder(XyOffset.of(40f, lp.yPageTop())).addCellWidths(vec(120f, 120f, 120f)).textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder().cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK))).rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder().cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY))).minRowHeight(120f).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder().cellBuilder().align(TOP_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder().cellBuilder().align(MIDDLE_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(MIDDLE_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(MIDDLE_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder().cellBuilder().align(BOTTOM_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(BOTTOM_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(BOTTOM_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().buildPart().buildTable();
// Where's the lower-right-hand corner? Put a cell there.
lp.tableBuilder(XyOffset.of(lp.pageWidth() - (100 + pMargin), lp.yPageBottom() + 15 + pMargin)).addCellWidths(vec(100f)).textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder().cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK))).rowBuilder().addTextCells("Lower-Right").buildRow().buildPart().buildTable();
lp.commit();
// More landscape pages
lp = pageMgr.logicalPageStart();
TextStyle pageHeadTextStyle = TextStyle.of(PDType1Font.HELVETICA, 7f, BLACK);
CellStyle pageHeadCellStyle = CellStyle.of(TOP_CENTER, null, null, null);
lp.putCellAsHeaderFooter(pMargin, lp.yPageTop() + 10, Cell.of(pageHeadCellStyle, tableWidth, pageHeadTextStyle, "Test Logical Page Three"));
// y = pageMgr.putRect(XyPair.of(pMargin, y), XyPair.of(100f,100f), Color.BLUE).y();
// We're going to reset and reuse this y variable.
float y = lp.yPageTop();
y = lp.putRow(pMargin, y, Cell.of(headingCell, colWidths[0], heading, "Transliterated Russian (with un-transliterated Chinese below)"), Cell.of(headingCellR, colWidths[1], heading, "US English"), Cell.of(headingCellR, colWidths[2], heading, "Finnish"), Cell.of(headingCellR, colWidths[3], heading, "German"));
File f = new File("target/test-classes/melon.jpg");
System.out.println(f.getAbsolutePath());
BufferedImage melonPic = ImageIO.read(f);
y = lp.putRow(pMargin, y, Cell.builder(regularCell, colWidths[0]).add(regular, vec("РоÑ?Ñ?иÑ? – Ñ?вÑ?щеннаÑ? наша держава,", "РоÑ?Ñ?иÑ? – любимаÑ? наша Ñ?трана.", "МогучаÑ? волÑ?, великаÑ? Ñ?лава –", "Твоё доÑ?тоÑ?нье на вÑ?е времена!", null, "Chorus:", null, "СлавьÑ?Ñ?, ОтечеÑ?тво наше Ñ?вободное, БратÑ?ких народов Ñ?оюз" + " вековой, Предками даннаÑ? мудроÑ?ть народнаÑ?! СлавьÑ?Ñ?, Ñ?трана!" + " Мы гордимÑ?Ñ? тобой!", null, "От южных морей до полÑ?рного краÑ? РаÑ?кинулиÑ?ÑŒ наши леÑ?а и" + " полÑ?. Одна ты на Ñ?вете! Одна ты такаÑ? – ХранимаÑ? Богом " + "роднаÑ? землÑ?!", null, "Chorus:", null, "Широкий проÑ?тор длÑ? мечты и длÑ? жизни", "ГрÑ?дущие нам открывают года.", "Ð?ам Ñ?илу даёт наша верноÑ?ть Отчизне.", "Так было, так еÑ?ть и так будет вÑ?егда!", null, "Chorus", null, null, null, "Chinese will not print. The substitution character is a" + " bullet, so below should be lots of bullets.", null, "起來ï¼?ä¸?願å?šå¥´éš¸çš„人們ï¼? " + "把我們的血肉,築æˆ?我們新的長城ï¼? " + "ä¸è?¯æ°‘æ—?到了最å?±éšªçš„æ™‚候, " + "æ¯?個人被迫著發出最後的å?¼è?²ã€‚ " + "起來ï¼?起來ï¼?起來ï¼? " + "我們è?¬çœ¾ä¸€å¿ƒï¼Œ " + "冒著敵人的炮ç?«ï¼Œå‰?進ï¼? " + "冒著敵人的炮ç?«ï¼Œå‰?進ï¼? " + "å‰?進ï¼?å‰?進ï¼?進ï¼?", null, "Here is a picture with the default and other sizes. Though" + " it shows up several times, the image data is only attached" + " to the file once and reused.")).add(ScaledJpeg.of(melonPic), ScaledJpeg.of(melonPic, 50, 50), ScaledJpeg.of(melonPic, 50, 50), ScaledJpeg.of(melonPic, 170, 100)).build(), Cell.builder(regularCell, colWidths[1]).add(regular, // Flowing text
vec("O say can you see by the dawn's early light, " + "What so proudly we hailed at the twilight's last gleaming, " + "Whose broad stripes and bright stars " + "through the perilous fight, " + "O'er the ramparts we watched, were so gallantly streaming? " + "And the rockets' red glare, the bombs bursting in air, " + "Gave proof through the night that our flag was still there; " + "O say does that star-spangled banner yet wave, " + "O'er the land of the free and the home of the brave? ", // Tiny space
null, // Set line breaks:
"On the shore dimly seen through the mists of the deep, ", "Where the foe's haughty host in dread silence reposes, ", "What is that which the breeze, o'er the towering steep, ", "As it fitfully blows, half conceals, half discloses? ", "Now it catches the gleam of the morning's first beam, ", "In full glory reflected now shines in the stream: ", "'Tis the star-spangled banner, O! long may it wave ", "O'er the land of the free and the home of the brave. ", // Big space.
null, null, null, null, null, null, null, null, // Flowing text
"And where is that band who so vauntingly swore " + "That the havoc of war and the battle's confusion, " + "A home and a country, should leave us no more? " + "Their blood has washed out their foul footsteps' pollution. " + "No refuge could save the hireling and slave " + "From the terror of flight, or the gloom of the grave: " + "And the star-spangled banner in triumph doth wave, " + "O'er the land of the free and the home of the brave. " + null, "O thus be it ever, when freemen shall stand " + "Between their loved home and the war's desolation. " + "Blest with vict'ry and peace, may the Heav'n rescued land " + "Praise the Power that hath made and preserved us a nation! " + "Then conquer we must, when our cause it is just, " + "And this be our motto: \"In God is our trust.\" " + "And the star-spangled banner in triumph shall wave " + "O'er the land of the free and the home of the brave!")).build(), Cell.builder(regularCell, colWidths[2]).add(regular, vec("Maamme", null, "Monument to the Vårt Land poem in Helsinki. " + "Oi maamme, Suomi, synnyinmaa, " + "soi, sana kultainen! " + "Ei laaksoa, ei kukkulaa, " + "ei vettä, rantaa rakkaampaa " + "kuin kotimaa tää pohjoinen, " + "maa kallis isien. " + "Sun kukoistukses kuorestaan " + "kerrankin puhkeaa; " + "viel' lempemme saa nousemaan " + "sun toivos, riemus loistossaan, " + "ja kerran laulus, synnyinmaa " + "korkeemman kaiun saa. ", null, "Vårt land ", null, "(the original, by Johan Ludvig Runeberg) " + "Vårt land, vårt land, vårt fosterland, " + "ljud högt, o dyra ord! " + "Ej lyfts en höjd mot himlens rand, " + "ej sänks en dal, ej sköljs en strand, " + "mer älskad än vår bygd i nord, " + "än våra fäders jord! " + "Din blomning, sluten än i knopp, " + "Skall mogna ur sitt tvång; " + "Se, ur vår kärlek skall gå opp " + "Ditt ljus, din glans, din fröjd, ditt hopp. " + "Och högre klinga skall en gång " + "Vår fosterländska sång.")).build(), Cell.builder(regularCell, colWidths[3]).add(regular, vec(// Older first 2 verses obsolete.
"Einigkeit und Recht und Freiheit " + "Für das deutsche Vaterland! " + "Danach lasst uns alle streben " + "Brüderlich mit Herz und Hand! " + "Einigkeit und Recht und Freiheit " + "Sind des Glückes Unterpfand;" + "Blüh' im Glanze dieses Glückes, " + " Blühe, deutsches Vaterland!")).build());
lp.putRow(pMargin, y, Cell.of(regularCell, colWidths[0], regular, "Another row of cells"), Cell.of(regularCell, colWidths[1], regular, "On the second page"), Cell.of(regularCell, colWidths[2], regular, "Just like any other page"), Cell.of(regularCell, colWidths[3], regular, "That's it!"));
lp.commit();
final LineStyle lineStyle = LineStyle.of(BLACK, 1);
lp = pageMgr.logicalPageStart();
lp.putCellAsHeaderFooter(pMargin, lp.yPageTop() + 10, Cell.of(pageHeadCellStyle, tableWidth, pageHeadTextStyle, "Test Logical Page Four"));
// Make a big 3-page X in a box. Notice that we code it as though it's on one page, and the
// API adds two more pages as needed. This is a great test for how geometric shapes break
// across pages.
// top lne
lp.putLine(pMargin, lp.yPageTop(), pageRMargin, lp.yPageTop(), lineStyle);
// left line
lp.putLine(pMargin, lp.yPageTop(), pMargin, -lp.yPageTop(), lineStyle);
// 3-page-long X
lp.putLine(pMargin, lp.yPageTop(), pageRMargin, -lp.yPageTop(), lineStyle);
// middle line
lp.putLine(pMargin, 0, pageRMargin, 0, lineStyle);
lp.putLine(pageRMargin, lp.yPageTop(), pMargin, -lp.yPageTop(), lineStyle);
// right line
lp.putLine(pageRMargin, lp.yPageTop(), pageRMargin, -lp.yPageTop(), lineStyle);
// bottom line
lp.putLine(pMargin, -lp.yPageTop(), pageRMargin, -lp.yPageTop(), lineStyle);
lp.commit();
// All done - write it out!
// In a web application, this could be:
//
// httpServletResponse.setContentType("application/pdf") // your server may do this for you.
// os = httpServletResponse.getOutputStream() // you probably have to do this
//
// Also, in a web app, you probably want name your action something.pdf and put
// target="_blank" on your link to the PDF download action.
// We're just going to write to a file.
OutputStream os = new FileOutputStream("test.pdf");
// Commit it to the output stream!
pageMgr.save(os);
}Example 2
| Project: tabula-java-master File: TestTextElement.java View source code |
@Test
public void createTextElement() throws IOException {
TextElement textElement = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f);
Assert.assertNotNull(textElement);
Assert.assertEquals("A", textElement.getText());
Assert.assertEquals(1f, textElement.getFontSize(), 0);
Assert.assertEquals(15f, textElement.getLeft(), 0);
Assert.assertEquals(5f, textElement.getTop(), 0);
Assert.assertEquals(10f, textElement.getWidth(), 0);
Assert.assertEquals(20f, textElement.getHeight(), 0);
Assert.assertEquals(PDType1Font.HELVETICA, textElement.getFont());
Assert.assertEquals(1f, textElement.getWidthOfSpace(), 0);
Assert.assertEquals(0f, textElement.getDirection(), 0);
}Example 3
| Project: brigen-base-master File: PdfWriterBuilderTest.java View source code |
@Override
protected void build(PDDocument doc, Void data) throws IOException {
for (int i = 0; i < 3; i++) {
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
contentStream.beginText();
contentStream.moveTextPositionByAmount(300, 100);
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 20);
contentStream.drawString("1 - " + i);
contentStream.endText();
contentStream.close();
}
}Example 4
| Project: OpenLegislation-master File: TranscriptPdfView.java View source code |
public static void writeTranscriptPdf(Transcript transcript, OutputStream outputStream) throws IOException, COSVisitorException {
if (transcript == null) {
throw new IllegalArgumentException("Supplied transcript cannot be null when converting to pdf.");
}
try (PDDocument doc = new PDDocument()) {
PDFont font = PDType1Font.COURIER;
List<List<String>> pages = TranscriptTextUtils.getPdfFormattedPages(transcript.getText());
for (List<String> page : pages) {
PDPage pg = new PDPage(PDPage.PAGE_SIZE_LETTER);
PDPageContentStream contentStream = new PDPageContentStream(doc, pg);
drawBorder(contentStream);
contentStream.beginText();
contentStream.setFont(font, fontSize);
moveStreamToTopOfPage(contentStream);
int lineCount = drawPageText(page, contentStream);
drawStenographer(transcript, contentStream, lineCount);
contentStream.endText();
contentStream.close();
doc.addPage(pg);
}
doc.save(outputStream);
}
}Example 5
| Project: pdfbox-master File: PDAcroForm.java View source code |
/*
* Verify that there are default entries for required
* properties.
*
* If these are missing create default entries similar to
* Adobe Reader / Adobe Acrobat
*
*/
private void verifyOrCreateDefaults() {
// TODO: the handling of the missing properties is suitable
// if there are no entries at all. It might be necessary to enhance that
// if only parts are missing
final String AdobeDefaultAppearanceString = "/Helv 0 Tf 0 g ";
// DA entry is required
if (getDefaultAppearance().length() == 0) {
setDefaultAppearance(AdobeDefaultAppearanceString);
}
// DR entry is required
if (getDefaultResources() == null) {
// Adobe Acrobat uses Helvetica as a default font and
// stores that under the name '/Helv' in the resources dictionary
// Zapf Dingbats is included per default for check boxes and
// radio buttons as /ZaDb.
PDResources resources = new PDResources();
resources.put(COSName.getPDFName("Helv"), PDType1Font.HELVETICA);
resources.put(COSName.getPDFName("ZaDb"), PDType1Font.ZAPF_DINGBATS);
setDefaultResources(resources);
}
}Example 6
| Project: with-aes-master File: Annotation.java View source code |
/**
* This will create a doucument showing various annotations.
*
* @param args The command line arguments.
*
* @throws Exception If there is an error parsing the document.
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
usage();
} else {
PDDocument document = new PDDocument();
try {
PDPage page = new PDPage();
document.addPage(page);
List annotations = page.getAnnotations();
// Setup some basic reusable objects/constants
// Annotations themselves can only be used once!
float inch = 72;
PDGamma colourRed = new PDGamma();
colourRed.setR(1);
PDGamma colourBlue = new PDGamma();
colourBlue.setB(1);
PDGamma colourBlack = new PDGamma();
PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
// 12th inch
borderThick.setWidth(inch / 12);
PDBorderStyleDictionary borderThin = new PDBorderStyleDictionary();
// 1 point
borderThin.setWidth(inch / 72);
PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary();
borderULine.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
// 1 point
borderULine.setWidth(inch / 72);
float pw = page.getMediaBox().getUpperRightX();
float ph = page.getMediaBox().getUpperRightY();
// First add some text, two lines we'll add some annotations to this later
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(font, 18);
contentStream.moveTextPositionByAmount(inch, ph - inch - 18);
contentStream.drawString("PDFBox");
contentStream.moveTextPositionByAmount(0, -(inch / 2));
contentStream.drawString("Click Here");
contentStream.endText();
contentStream.close();
// Now add the markup annotation, a highlight to PDFBox text
PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
txtMark.setColour(colourBlue);
// Make the highlight 20% transparent
txtMark.setConstantOpacity((float) 0.2);
// Set the rectangle containing the markup
float textWidth = (font.getStringWidth("PDFBox") / 1000) * 18;
PDRectangle position = new PDRectangle();
position.setLowerLeftX(inch);
position.setLowerLeftY(ph - inch - 18);
position.setUpperRightX(72 + textWidth);
position.setUpperRightY(ph - inch);
txtMark.setRectangle(position);
// work out the points forming the four corners of the annotations
// set out in anti clockwise form (Completely wraps the text)
// OK, the below doesn't match that description.
// It's what acrobat 7 does and displays properly!
float[] quads = new float[8];
// x1
quads[0] = position.getLowerLeftX();
// y1
quads[1] = position.getUpperRightY() - 2;
// x2
quads[2] = position.getUpperRightX();
// y2
quads[3] = quads[1];
// x3
quads[4] = quads[0];
// y3
quads[5] = position.getLowerLeftY() - 2;
// x4
quads[6] = quads[2];
// y5
quads[7] = quads[5];
txtMark.setQuadPoints(quads);
txtMark.setContents("Highlighted since it's important");
annotations.add(txtMark);
// Now add the link annotation, so the clickme works
PDAnnotationLink txtLink = new PDAnnotationLink();
txtLink.setBorderStyle(borderULine);
// Set the rectangle containing the link
textWidth = (font.getStringWidth("Click Here") / 1000) * 18;
position = new PDRectangle();
position.setLowerLeftX(inch);
// down a couple of points
position.setLowerLeftY(ph - (float) (1.5 * inch) - 20);
position.setUpperRightX(72 + textWidth);
position.setUpperRightY(ph - (float) (1.5 * inch));
txtLink.setRectangle(position);
// add an action
PDActionURI action = new PDActionURI();
action.setURI("http://www.pdfbox.org");
txtLink.setAction(action);
annotations.add(txtLink);
// Now draw a few more annotations
PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
aCircle.setContents("Circle Annotation");
// Fill in circle in red
aCircle.setInteriorColour(colourRed);
// The border itself will be blue
aCircle.setColour(colourBlue);
aCircle.setBorderStyle(borderThin);
// Place the annotation on the page, we'll make this 1" round
// 3" down, 1" in on the page
position = new PDRectangle();
position.setLowerLeftX(inch);
// 1" height, 3" down
position.setLowerLeftY(ph - (3 * inch) - inch);
// 1" in, 1" width
position.setUpperRightX(2 * inch);
// 3" down
position.setUpperRightY(ph - (3 * inch));
aCircle.setRectangle(position);
// add to the annotations on the page
annotations.add(aCircle);
// Now a square annotation
PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
aSquare.setContents("Square Annotation");
// Outline in red, not setting a fill
aSquare.setColour(colourRed);
aSquare.setBorderStyle(borderThick);
// Place the annotation on the page, we'll make this 1" (72points) square
// 3.5" down, 1" in from the right on the page
// Reuse the variable, but note it's a new object!
position = new PDRectangle();
// 1" in from right, 1" wide
position.setLowerLeftX(pw - (2 * inch));
// 1" height, 3.5" down
position.setLowerLeftY(ph - (float) (3.5 * inch) - inch);
// 1" in from right
position.setUpperRightX(pw - inch);
// 3.5" down
position.setUpperRightY(ph - (float) (3.5 * inch));
aSquare.setRectangle(position);
// add to the annotations on the page
annotations.add(aSquare);
// Now we want to draw a line between the two, one end with an open arrow
PDAnnotationLine aLine = new PDAnnotationLine();
aLine.setEndPointEndingStyle(PDAnnotationLine.LE_OPEN_ARROW);
aLine.setContents("Circle->Square");
// Make the contents a caption on the line
aLine.setCaption(true);
// Set the rectangle containing the line
// Reuse the variable, but note it's a new object!
position = new PDRectangle();
// 1" in + width of circle
position.setLowerLeftX(2 * inch);
// 1" height, 3.5" down
position.setLowerLeftY(ph - (float) (3.5 * inch) - inch);
// 1" in from right, and width of square
position.setUpperRightX(pw - inch - inch);
// 3" down (top of circle)
position.setUpperRightY(ph - (3 * inch));
aLine.setRectangle(position);
// Now set the line position itself
float[] linepos = new float[4];
// x1 = rhs of circle
linepos[0] = 2 * inch;
// y1 halfway down circle
linepos[1] = ph - (float) (3.5 * inch);
// x2 = lhs of square
linepos[2] = pw - (2 * inch);
// y2 halfway down square
linepos[3] = ph - (4 * inch);
aLine.setLine(linepos);
aLine.setBorderStyle(borderThick);
aLine.setColour(colourBlack);
// add to the annotations on the page
annotations.add(aLine);
// Finally all done
document.save(args[0]);
} finally {
document.close();
}
}
}Example 7
| Project: nuxeo-versions-difference-master File: TestPdfBoxN.java View source code |
public void create(String message, String outfile) throws IOException, COSVisitorException {
PDDocument doc = null;
try {
doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
PDFont font = PDType1Font.HELVETICA;
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(100, 700);
contentStream.drawString(message);
contentStream.endText();
contentStream.close();
doc.save(outfile);
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 8
| Project: PDF-to-unusual-HTML-master File: Annotation.java View source code |
/**
* This will create a doucument showing various annotations.
*
* @param args The command line arguments.
*
* @throws Exception If there is an error parsing the document.
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
usage();
} else {
PDDocument document = new PDDocument();
try {
PDPage page = new PDPage();
document.addPage(page);
List annotations = page.getAnnotations();
// Setup some basic reusable objects/constants
// Annotations themselves can only be used once!
float inch = 72;
PDGamma colourRed = new PDGamma();
colourRed.setR(1);
PDGamma colourBlue = new PDGamma();
colourBlue.setB(1);
PDGamma colourBlack = new PDGamma();
PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
// 12th inch
borderThick.setWidth(inch / 12);
PDBorderStyleDictionary borderThin = new PDBorderStyleDictionary();
// 1 point
borderThin.setWidth(inch / 72);
PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary();
borderULine.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
// 1 point
borderULine.setWidth(inch / 72);
float pw = page.getMediaBox().getUpperRightX();
float ph = page.getMediaBox().getUpperRightY();
// First add some text, two lines we'll add some annotations to this later
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(font, 18);
contentStream.moveTextPositionByAmount(inch, ph - inch - 18);
contentStream.drawString("PDFBox");
contentStream.moveTextPositionByAmount(0, -(inch / 2));
contentStream.drawString("Click Here");
contentStream.endText();
contentStream.close();
// Now add the markup annotation, a highlight to PDFBox text
PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
txtMark.setColour(colourBlue);
// Make the highlight 20% transparent
txtMark.setConstantOpacity((float) 0.2);
// Set the rectangle containing the markup
float textWidth = (font.getStringWidth("PDFBox") / 1000) * 18;
PDRectangle position = new PDRectangle();
position.setLowerLeftX(inch);
position.setLowerLeftY(ph - inch - 18);
position.setUpperRightX(72 + textWidth);
position.setUpperRightY(ph - inch);
txtMark.setRectangle(position);
// work out the points forming the four corners of the annotations
// set out in anti clockwise form (Completely wraps the text)
// OK, the below doesn't match that description.
// It's what acrobat 7 does and displays properly!
float[] quads = new float[8];
// x1
quads[0] = position.getLowerLeftX();
// y1
quads[1] = position.getUpperRightY() - 2;
// x2
quads[2] = position.getUpperRightX();
// y2
quads[3] = quads[1];
// x3
quads[4] = quads[0];
// y3
quads[5] = position.getLowerLeftY() - 2;
// x4
quads[6] = quads[2];
// y5
quads[7] = quads[5];
txtMark.setQuadPoints(quads);
txtMark.setContents("Highlighted since it's important");
annotations.add(txtMark);
// Now add the link annotation, so the clickme works
PDAnnotationLink txtLink = new PDAnnotationLink();
txtLink.setBorderStyle(borderULine);
// Set the rectangle containing the link
textWidth = (font.getStringWidth("Click Here") / 1000) * 18;
position = new PDRectangle();
position.setLowerLeftX(inch);
// down a couple of points
position.setLowerLeftY(ph - (float) (1.5 * inch) - 20);
position.setUpperRightX(72 + textWidth);
position.setUpperRightY(ph - (float) (1.5 * inch));
txtLink.setRectangle(position);
// add an action
PDActionURI action = new PDActionURI();
action.setURI("http://www.pdfbox.org");
txtLink.setAction(action);
annotations.add(txtLink);
// Now draw a few more annotations
PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
aCircle.setContents("Circle Annotation");
// Fill in circle in red
aCircle.setInteriorColour(colourRed);
// The border itself will be blue
aCircle.setColour(colourBlue);
aCircle.setBorderStyle(borderThin);
// Place the annotation on the page, we'll make this 1" round
// 3" down, 1" in on the page
position = new PDRectangle();
position.setLowerLeftX(inch);
// 1" height, 3" down
position.setLowerLeftY(ph - (3 * inch) - inch);
// 1" in, 1" width
position.setUpperRightX(2 * inch);
// 3" down
position.setUpperRightY(ph - (3 * inch));
aCircle.setRectangle(position);
// add to the annotations on the page
annotations.add(aCircle);
// Now a square annotation
PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
aSquare.setContents("Square Annotation");
// Outline in red, not setting a fill
aSquare.setColour(colourRed);
aSquare.setBorderStyle(borderThick);
// Place the annotation on the page, we'll make this 1" (72points) square
// 3.5" down, 1" in from the right on the page
// Reuse the variable, but note it's a new object!
position = new PDRectangle();
// 1" in from right, 1" wide
position.setLowerLeftX(pw - (2 * inch));
// 1" height, 3.5" down
position.setLowerLeftY(ph - (float) (3.5 * inch) - inch);
// 1" in from right
position.setUpperRightX(pw - inch);
// 3.5" down
position.setUpperRightY(ph - (float) (3.5 * inch));
aSquare.setRectangle(position);
// add to the annotations on the page
annotations.add(aSquare);
// Now we want to draw a line between the two, one end with an open arrow
PDAnnotationLine aLine = new PDAnnotationLine();
aLine.setEndPointEndingStyle(PDAnnotationLine.LE_OPEN_ARROW);
aLine.setContents("Circle->Square");
// Make the contents a caption on the line
aLine.setCaption(true);
// Set the rectangle containing the line
// Reuse the variable, but note it's a new object!
position = new PDRectangle();
// 1" in + width of circle
position.setLowerLeftX(2 * inch);
// 1" height, 3.5" down
position.setLowerLeftY(ph - (float) (3.5 * inch) - inch);
// 1" in from right, and width of square
position.setUpperRightX(pw - inch - inch);
// 3" down (top of circle)
position.setUpperRightY(ph - (3 * inch));
aLine.setRectangle(position);
// Now set the line position itself
float[] linepos = new float[4];
// x1 = rhs of circle
linepos[0] = 2 * inch;
// y1 halfway down circle
linepos[1] = ph - (float) (3.5 * inch);
// x2 = lhs of square
linepos[2] = pw - (2 * inch);
// y2 halfway down square
linepos[3] = ph - (4 * inch);
aLine.setLine(linepos);
aLine.setBorderStyle(borderThick);
aLine.setColour(colourBlack);
// add to the annotations on the page
annotations.add(aLine);
// Finally all done
document.save(args[0]);
} finally {
document.close();
}
}
}Example 9
| Project: yacy_search_server-master File: pdfParser.java View source code |
public static void clean_up_idiotic_PDFParser_font_cache_which_eats_up_tons_of_megabytes() {
// thank you very much, PDFParser hackers, this font cache will occupy >80MB RAM for a single pdf and then stays forever
// AND I DO NOT EVEN NEED A FONT HERE TO PARSE THE TEXT!
// Don't be so ignorant, just google once "PDFParser OutOfMemoryError" to feel the pain.
ResourceCleaner cl = new ResourceCleaner();
cl.clearClassResources("org.apache.pdfbox.cos.COSName");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType1Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDTrueTypeFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType0Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType1AfmPfbFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType3Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType1CFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDCIDFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDCIDFontType0Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDCIDFontType2Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDMMType1Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDSimpleFont");
}Example 10
| Project: camel-master File: PdfTextExtractionTest.java View source code |
@Test
public void testExtractText() throws Exception {
final String expectedText = "Test string";
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.beginText();
contentStream.moveTextPositionByAmount(20, 400);
contentStream.drawString(expectedText);
contentStream.endText();
contentStream.close();
template.sendBody("direct:start", document);
resultEndpoint.setExpectedMessageCount(1);
resultEndpoint.expectedMessagesMatches(new Predicate() {
@Override
public boolean matches(Exchange exchange) {
Object body = exchange.getIn().getBody();
assertThat(body, instanceOf(String.class));
assertThat((String) body, containsString(expectedText));
return true;
}
});
resultEndpoint.assertIsSatisfied();
}Example 11
| Project: CZ3003_Backend-master File: CReport.java View source code |
public static void genReport(JSONArray pObjAry) throws IOException, COSVisitorException {
String imagePath = "C:\\Users\\Bryden\\Desktop\\pie-sample.png";
List<List<String>> lstContents = new ArrayList<>();
List<String> aryLst = new ArrayList<>();
aryLst.add("Incident Type");
aryLst.add("");
lstContents.add(aryLst);
for (Object obj : pObjAry) {
JSONObject objJson = (JSONObject) obj;
Iterator<?> keys = objJson.keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
// loop to get the dynamic key
String value = (String) objJson.get(key);
List<String> aryValues = new ArrayList<>();
aryValues.add(key);
aryValues.add(value);
lstContents.add(aryValues);
}
}
try (// Create a document and add a page to it
PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
InputStream in = Files.newInputStream(Paths.get(imagePath));
PDJpeg img = new PDJpeg(document, in);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
try (// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.beginText();
contentStream.setFont(font, 20);
contentStream.moveTextPositionByAmount(70, 720);
contentStream.drawString("Incident Summary " + new Date());
contentStream.endText();
contentStream.beginText();
contentStream.setFont(font, 20);
contentStream.moveTextPositionByAmount(100, 670);
contentStream.drawString("Statistics");
contentStream.endText();
contentStream.drawImage(img, 10, 10);
drawTable(page, contentStream, 650, 100, lstContents);
// Make sure that the content stream is closed:
}
img.clear();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
}
}Example 12
| Project: infoLink-master File: InfolisBaseTest.java View source code |
protected List<InfolisFile> createTestPdfFiles(int nrFiles, String[] testStrings) throws Exception {
List<InfolisFile> ret = new ArrayList<>();
int j = 0;
for (int i = 0; i < nrFiles; i++) {
j = i % testStrings.length;
String data = testStrings[j];
Path tempFile = Files.createTempFile("infolis-", ".pdf");
// create the pdf
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.moveTextPositionByAmount(100, 100);
contentStream.drawString(data);
contentStream.endText();
contentStream.close();
// Important, otherwise hashing won't work because different random ID
document.setDocumentId(0L);
// Save to temp file
OutputStream tempOut = Files.newOutputStream(tempFile);
document.save(tempOut);
document.close();
tempOut.close();
// create infolis file
InfolisFile file = new InfolisFile();
file.setMd5(SerializationUtils.getHexMd5(IOUtils.toByteArray(Files.newInputStream(tempFile))));
file.setFileName(tempFile.toString());
file.setFileStatus("AVAILABLE");
file.setMediaType("application/pdf");
// Write the data to the file
OutputStream os = fileResolver.openOutputStream(file);
IOUtils.copy(Files.newInputStream(tempFile), os);
os.close();
Entity entity = new Entity();
dataStoreClient.post(Entity.class, entity);
file.setManifestsEntity(entity.getUri());
dataStoreClient.post(InfolisFile.class, file);
ret.add(file);
}
return ret;
}Example 13
| Project: amos-ss15-proj4-master File: ZipGenerator.java View source code |
public void generate(OutputStream out, Locale locale, float height, Employee employee, int fontSize, String zipPassword) throws ZipException, NoSuchMessageException, IOException, COSVisitorException, CloneNotSupportedException {
final ZipOutputStream zout = new ZipOutputStream(out);
if (zipPassword == null) {
// Use default password if none is set.
zipPassword = "fragebogen";
}
ZipParameters params = new ZipParameters();
params.setFileNameInZip("employee.txt");
params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE);
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
params.setEncryptFiles(true);
params.setReadHiddenFiles(false);
params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
params.setPassword(zipPassword);
params.setSourceExternalStream(true);
zout.putNextEntry(null, params);
zout.write((AppContext.getApplicationContext().getMessage("HEADER", null, locale) + "\n\n").getBytes());
zout.write((AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale) + "\n\n").getBytes());
Iterator it = employee.getPersonalDataFields().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
// avoids a ConcurrentModificationException
it.remove();
}
zout.write(("\n\n" + AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale) + "\n\n").getBytes());
it = employee.getTaxesFields().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
// avoids a ConcurrentModificationException
it.remove();
}
zout.closeEntry();
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
float y = -1;
int margin = 100;
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.TIMES_ROMAN;
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.beginText();
y = page.getMediaBox().getHeight() - margin + height;
contentStream.moveTextPositionByAmount(margin, y);
/*
List<String> list = StringUtils.splitEqually(fileContent, 90);
for (String e : list) {
contentStream.moveTextPositionByAmount(0, -15);
contentStream.drawString(e);
}
*/
contentStream.setFont(PDType1Font.TIMES_BOLD, 36);
contentStream.drawString(AppContext.getApplicationContext().getMessage("HEADER", null, locale));
contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
contentStream.moveTextPositionByAmount(0, -4 * height);
contentStream.drawString(AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale));
contentStream.moveTextPositionByAmount(0, -2 * height);
contentStream.setFont(font, fontSize);
it = employee.getPersonalDataFields().entrySet().iterator();
while (it.hasNext()) {
StringBuffer nextLineToDraw = new StringBuffer();
Map.Entry pair = (Map.Entry) it.next();
nextLineToDraw.append(pair.getKey());
nextLineToDraw.append(": ");
nextLineToDraw.append(pair.getValue());
contentStream.drawString(nextLineToDraw.toString());
contentStream.moveTextPositionByAmount(0, -height);
// avoids a ConcurrentModificationException
it.remove();
}
contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
contentStream.moveTextPositionByAmount(0, -2 * height);
contentStream.drawString(AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale));
contentStream.moveTextPositionByAmount(0, -2 * height);
contentStream.setFont(font, fontSize);
it = employee.getTaxesFields().entrySet().iterator();
while (it.hasNext()) {
StringBuffer nextLineToDraw = new StringBuffer();
Map.Entry pair = (Map.Entry) it.next();
nextLineToDraw.append(pair.getKey());
nextLineToDraw.append(": ");
nextLineToDraw.append(pair.getValue());
contentStream.drawString(nextLineToDraw.toString());
contentStream.moveTextPositionByAmount(0, -height);
// avoids a ConcurrentModificationException
it.remove();
}
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
ByteArrayOutputStream pdfout = new ByteArrayOutputStream();
document.save(pdfout);
document.close();
ZipParameters params2 = (ZipParameters) params.clone();
params2.setFileNameInZip("employee.pdf");
zout.putNextEntry(null, params2);
zout.write(pdfout.toByteArray());
zout.closeEntry();
// Write the zip to client
zout.finish();
zout.flush();
zout.close();
}Example 14
| Project: elexis-3-base-master File: PrintVaccinationEntriesHandler.java View source code |
private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
PDDocumentInformation pdi = new PDDocumentInformation();
Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
pdi.setCreationDate(new GregorianCalendar());
pdi.setTitle("Impfausweis " + patient.getLabel());
PDDocument document = new PDDocument();
document.setDocumentInformation(pdi);
PDPage page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
document.addPage(page);
PDRectangle pageSize = page.findMediaBox();
PDFont font = PDType1Font.HELVETICA_BOLD;
PDFont subFont = PDType1Font.HELVETICA;
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(font, 14);
contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
contentStream.drawString(patient.getLabel());
contentStream.endText();
String dateLabel = sdf.format(Calendar.getInstance().getTime());
String title = Person.load(mandant.getId()).get(Person.TITLE);
String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
contentStream.beginText();
contentStream.setFont(subFont, 10);
contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
contentStream.endText();
BufferedImage imageAwt = convertToAWT(image.getImageData());
PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
contentStream.close();
String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR, CoreHub.getWritableUserDir().getAbsolutePath());
if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
}
File outputDir = new File(outputPath);
File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
document.save(pdf);
document.close();
Desktop.getDesktop().open(pdf);
}Example 15
| Project: is.idega.idegaweb.marathon-master File: PDFTester.java View source code |
public void doIt(String message, String outfile) throws IOException, COSVisitorException {
// the document
PDDocument doc = null;
try {
doc = new PDDocument();
// Page 1
PDFont font = PDType1Font.HELVETICA;
PDPage page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
float fontSize = 12.0f;
PDRectangle pageSize = page.findMediaBox();
float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f;
float stringWidth = font.getStringWidth(message);
float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f;
PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
contentStream.setFont(font, fontSize);
contentStream.beginText();
// counterclockwise rotation
for (int i = 0; i < 8; i++) {
contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition);
contentStream.drawString(message + " " + i);
}
// clockwise rotation
for (int i = 0; i < 8; i++) {
contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition);
contentStream.drawString(message + " " + i);
}
contentStream.endText();
contentStream.close();
// Page 2
page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
fontSize = 1.0f;
contentStream = new PDPageContentStream(doc, page, false, false);
contentStream.setFont(font, fontSize);
contentStream.beginText();
// text scaling
for (int i = 0; i < 10; i++) {
contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50);
contentStream.drawString(message + " " + i);
}
contentStream.endText();
contentStream.close();
// Page 3
page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
fontSize = 1.0f;
contentStream = new PDPageContentStream(doc, page, false, false);
contentStream.setFont(font, fontSize);
contentStream.beginText();
int i = 0;
// text scaling combined with rotation
contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.endText();
contentStream.close();
doc.save(outfile);
} finally {
if (doc != null) {
doc.close();
}
}
}Example 16
| Project: streamflow-core-master File: PdfGeneratorService.java View source code |
public PDDocument generateSubmittedFormPdf(SubmittedFormValue value, CaseId.Data id, String templateUri, Locale locale) throws Throwable {
FormVisibilityRuleValidator visibilityValidator = module.objectBuilderFactory().newObjectBuilder(FormVisibilityRuleValidator.class).use(value).newInstance();
ResourceBundle bundle = ResourceBundle.getBundle(CasePdfGenerator.class.getName(), locale);
PdfGeneratorConfiguration pdfConfig = config.configuration();
PdfDocument document = new PdfDocument(PDPage.PAGE_SIZE_A4, pdfConfig.headerMargin().get(), pdfConfig.footerMargin().get(), pdfConfig.leftMargin().get(), pdfConfig.rightMargin().get());
document.init();
PdfFont h1Font = new PdfFont(PDType1Font.HELVETICA_BOLD, 16);
PdfFont h2Font = new PdfFont(PDType1Font.HELVETICA_BOLD, 14);
PdfFont valueFont = new PdfFont(PDType1Font.HELVETICA, 12);
PdfFont descFont = new PdfFont(PDType1Font.HELVETICA_OBLIQUE, 10);
PdfFont pageFont = new PdfFont(PDType1Font.HELVETICA_BOLD_OBLIQUE, 14);
Form form = module.unitOfWorkFactory().currentUnitOfWork().get(Form.class, value.form().get().identity());
document.print(bundle.getString("caseid") + ": " + id.caseId().get(), h1Font);
document.print(form.getDescription(), h2Font);
document.print(bundle.getString("submission_date") + ": " + DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(value.submissionDate().get()), descFont);
document.line();
for (SubmittedPageValue submittedPageValue : value.pages().get()) {
if (!visibilityValidator.visible(submittedPageValue))
continue;
Page page = module.unitOfWorkFactory().currentUnitOfWork().get(Page.class, submittedPageValue.page().get().identity());
document.print(page.getDescription(), pageFont);
// TODO Page breaks
for (SubmittedFieldValue submittedFieldValue : submittedPageValue.fields().get()) {
if (!visibilityValidator.visible(submittedFieldValue))
continue;
FieldEntity field = module.unitOfWorkFactory().currentUnitOfWork().get(FieldEntity.class, submittedFieldValue.field().get().identity());
document.print(field.getDescription() + ":", h2Font);
if (field.fieldValue().get() instanceof DateFieldValue && !empty(submittedFieldValue.value().get())) {
Date date = DateFunctions.fromString(submittedFieldValue.value().get());
document.print(DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(date), valueFont);
} else if (field.fieldValue().get() instanceof GeoLocationFieldValue) {
LocationDTO locationDTO = module.valueBuilderFactory().newValueFromJSON(LocationDTO.class, submittedFieldValue.value().get());
document.print(locationDTO.street().get() + ", " + locationDTO.zipcode().get() + ", " + locationDTO.city().get(), valueFont);
} else if (field.fieldValue().get() instanceof AttachmentFieldValue) {
try {
AttachmentFieldSubmission attachment = module.valueBuilderFactory().newValueFromJSON(AttachmentFieldSubmission.class, submittedFieldValue.value().get());
document.print(attachment.name().get(), valueFont);
} catch (ConstructionException e) {
}
} else {
document.print(submittedFieldValue.value().get(), valueFont);
}
document.print("", valueFont);
}
}
PDDocument submittedFormPdf = document.closeAndReturn();
submittedFormPdf.getDocumentInformation().setCreator("Streamflow");
Calendar calendar = Calendar.getInstance();
calendar.setTime(value.submissionDate().get());
submittedFormPdf.getDocumentInformation().setCreationDate(calendar);
submittedFormPdf.getDocumentInformation().setTitle(form.getDescription());
if (templateUri != null) {
String attachmentId = new URI(templateUri).getSchemeSpecificPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
store.attachment(attachmentId).transferTo(Outputs.byteBuffer(baos));
Underlay underlay = new Underlay();
submittedFormPdf = underlay.underlay(submittedFormPdf, new ByteArrayInputStream(baos.toByteArray()));
}
return submittedFormPdf;
}Example 17
| Project: DSpace-master File: CitationDocumentServiceImpl.java View source code |
protected void generateCoverPage(Context context, PDDocument document, PDPage coverPage, Item item) throws IOException {
PDPageContentStream contentStream = new PDPageContentStream(document, coverPage);
try {
int ypos = 760;
int xpos = 30;
int xwidth = 550;
int ygap = 20;
PDFont fontHelvetica = PDType1Font.HELVETICA;
PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
PDFont fontHelveticaOblique = PDType1Font.HELVETICA_OBLIQUE;
contentStream.setNonStrokingColor(Color.BLACK);
String[][] content = { header1 };
drawTable(coverPage, contentStream, ypos, xpos, content, fontHelveticaBold, 11, false);
ypos -= (ygap);
String[][] content2 = { header2 };
drawTable(coverPage, contentStream, ypos, xpos, content2, fontHelveticaBold, 11, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
String[][] content3 = { { getOwningCommunity(context, item), getOwningCollection(item) } };
drawTable(coverPage, contentStream, ypos, xpos, content3, fontHelvetica, 9, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap * 2);
for (String field : fields) {
field = field.trim();
PDFont font = fontHelvetica;
int fontSize = 11;
if (field.contains("title")) {
fontSize = 26;
ypos -= ygap;
} else if (field.contains("creator") || field.contains("contributor")) {
fontSize = 16;
}
if (field.equals("_line_")) {
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap);
} else if (StringUtils.isNotEmpty(itemService.getMetadata(item, field))) {
ypos = drawStringWordWrap(coverPage, contentStream, itemService.getMetadata(item, field), xpos, ypos, font, fontSize);
}
if (field.contains("title")) {
ypos -= ygap;
}
}
contentStream.beginText();
contentStream.setFont(fontHelveticaOblique, 11);
contentStream.moveTextPositionByAmount(xpos, ypos);
contentStream.drawString(footer);
contentStream.endText();
} finally {
contentStream.close();
}
}Example 18
| Project: dlibrary-master File: CitationDocument.java View source code |
private void generateCoverPage(PDDocument document, PDPage coverPage, Item item) throws IOException, COSVisitorException {
PDPageContentStream contentStream = new PDPageContentStream(document, coverPage);
try {
int ypos = 760;
int xpos = 30;
int xwidth = 550;
int ygap = 20;
PDFont fontHelvetica = PDType1Font.HELVETICA;
PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
PDFont fontHelveticaOblique = PDType1Font.HELVETICA_OBLIQUE;
contentStream.setNonStrokingColor(Color.BLACK);
String[][] content = { header1 };
drawTable(coverPage, contentStream, ypos, xpos, content, fontHelveticaBold, 11, false);
ypos -= (ygap);
String[][] content2 = { header2 };
drawTable(coverPage, contentStream, ypos, xpos, content2, fontHelveticaBold, 11, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
String[][] content3 = { { getOwningCommunity(item), getOwningCollection(item) } };
drawTable(coverPage, contentStream, ypos, xpos, content3, fontHelvetica, 9, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap * 2);
for (String field : fields) {
field = field.trim();
PDFont font = fontHelvetica;
int fontSize = 11;
if (field.contains("title")) {
fontSize = 26;
ypos -= ygap;
} else if (field.contains("creator") || field.contains("contributor")) {
fontSize = 16;
}
if (field.equals("_line_")) {
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap);
} else if (StringUtils.isNotEmpty(item.getMetadata(field))) {
ypos = drawStringWordWrap(coverPage, contentStream, item.getMetadata(field), xpos, ypos, font, fontSize);
}
if (field.contains("title")) {
ypos -= ygap;
}
}
contentStream.beginText();
contentStream.setFont(fontHelveticaOblique, 11);
contentStream.moveTextPositionByAmount(xpos, ypos);
contentStream.drawString(footer);
contentStream.endText();
} finally {
contentStream.close();
}
}Example 19
| Project: vtechworks-master File: CitationDocument.java View source code |
private void generateCoverPage(PDDocument document, PDPage coverPage, Item item) throws IOException, COSVisitorException {
PDPageContentStream contentStream = new PDPageContentStream(document, coverPage);
try {
int ypos = 760;
int xpos = 30;
int xwidth = 550;
int ygap = 20;
PDFont fontHelvetica = PDType1Font.HELVETICA;
PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
PDFont fontHelveticaOblique = PDType1Font.HELVETICA_OBLIQUE;
contentStream.setNonStrokingColor(Color.BLACK);
String[][] content = { header1 };
drawTable(coverPage, contentStream, ypos, xpos, content, fontHelveticaBold, 11, false);
ypos -= (ygap);
String[][] content2 = { header2 };
drawTable(coverPage, contentStream, ypos, xpos, content2, fontHelveticaBold, 11, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
String[][] content3 = { { getOwningCommunity(item), getOwningCollection(item) } };
drawTable(coverPage, contentStream, ypos, xpos, content3, fontHelvetica, 9, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap * 2);
for (String field : fields) {
field = field.trim();
PDFont font = fontHelvetica;
int fontSize = 11;
if (field.contains("title")) {
fontSize = 26;
ypos -= ygap;
} else if (field.contains("creator") || field.contains("contributor")) {
fontSize = 16;
}
if (field.equals("_line_")) {
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap);
} else if (StringUtils.isNotEmpty(item.getMetadata(field))) {
ypos = drawStringWordWrap(coverPage, contentStream, item.getMetadata(field), xpos, ypos, font, fontSize);
}
if (field.contains("title")) {
ypos -= ygap;
}
}
contentStream.beginText();
contentStream.setFont(fontHelveticaOblique, 11);
contentStream.moveTextPositionByAmount(xpos, ypos);
contentStream.drawString(footer);
contentStream.endText();
} finally {
contentStream.close();
}
}