Java Code Examples for com.lowagie.text.Document#newPage()
The following examples show how to use
com.lowagie.text.Document#newPage() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestPdfCopyAndStamp.java From itext2 with GNU Lesser General Public License v3.0 | 6 votes |
private void createTempFile(String filename, String[] pageContents) throws Exception{ Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); for (int i = 0; i < pageContents.length; i++) { if (i != 0) document.newPage(); String content = pageContents[i]; Chunk contentChunk = new Chunk(content); document.add(contentChunk); } document.close(); }
Example 2
Source File: SimplePdfTest.java From itext2 with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testSimplePdf() throws FileNotFoundException, DocumentException { // create document Document document = PdfTestBase.createPdf("testSimplePdf.pdf"); try { // new page with a rectangle document.open(); document.newPage(); Annotation ann = new Annotation("Title", "Text"); Rectangle rect = new Rectangle(100, 100); document.add(ann); document.add(rect); } finally { // close document if (document != null) document.close(); } }
Example 3
Source File: PdfDocumentWriter.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
public void processLogicalPage( final LogicalPageKey key, final LogicalPageBox logicalPage ) throws DocumentException { final float width = (float) StrictGeomUtility.toExternalValue( logicalPage.getPageWidth() ); final float height = (float) StrictGeomUtility.toExternalValue( logicalPage.getPageHeight() ); final Rectangle pageSize = new Rectangle( width, height ); final Document document = getDocument(); document.setPageSize( pageSize ); document.setMargins( 0, 0, 0, 0 ); if ( awaitOpenDocument ) { document.open(); awaitOpenDocument = false; } final Graphics2D graphics = new PdfGraphics2D( writer.getDirectContent(), width, height, metaData ); // and now process the box .. final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable( logicalPage, null ); logicalPageDrawable.draw( graphics, new Rectangle2D.Double( 0, 0, width, height ) ); graphics.dispose(); document.newPage(); }
Example 4
Source File: LocalDestinationTest.java From itext2 with GNU Lesser General Public License v3.0 | 6 votes |
/** * Creates a document that jumps to a Local Destination upon opening. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("LocalDestination.pdf")); // step 3: we open the document document.open(); // step 4: we add some content document.add(new Paragraph("Page 1")); document.newPage(); document.add(new Paragraph("This PDF file jumps directly to page 2 when opened")); PdfContentByte cb = writer.getDirectContent(); cb.localDestination("page2", new PdfDestination(PdfDestination.XYZ, -1, 10000, 0)); writer.setOpenAction("page2"); // step 5: we close the document document.close(); }
Example 5
Source File: PageLabelsTest.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
/** * Demonstrates some PageLabel functionality. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("PageLabels.pdf")); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseThumbs); document.open(); // step 4: // we add some content for (int k = 1; k <= 10; ++k) { document.add(new Paragraph( "This document has the logical page numbers: i,ii,iii,iv,1,2,3,A-8,A-9,A-10\nReal page " + k)); document.newPage(); } PdfPageLabels pageLabels = new PdfPageLabels(); pageLabels.addPageLabel(1, PdfPageLabels.LOWERCASE_ROMAN_NUMERALS); pageLabels.addPageLabel(5, PdfPageLabels.DECIMAL_ARABIC_NUMERALS); pageLabels.addPageLabel(8, PdfPageLabels.DECIMAL_ARABIC_NUMERALS, "A-", 8); writer.setPageLabels(pageLabels); // step 5: we close the document document.close(); }
Example 6
Source File: CashReceiptCoverSheetServiceImpl.java From kfs with GNU Affero General Public License v3.0 | 5 votes |
/** * Responsible for creating a new PDF page and workspace through <code>{@link PdfContentByte}</code> for direct writing to the * PDF. * * @param writer The PDF writer used to write to the new page with. * @param reader The PDF reader used to read information from the PDF file. * @param pageNumber The current number of pages in the PDF file, which will be incremented by one inside this method. * * @return The PDFContentByte used to access the new PDF page. * @exception DocumentException * @exception IOException */ protected PdfContentByte startNewPage(PdfWriter writer, PdfReader reader, ModifiableInteger pageNumber) throws DocumentException, IOException { PdfContentByte retval; PdfContentByte under; Rectangle pageSize; Document pdfDoc; PdfImportedPage newPage; pageNumber.increment(); pageSize = reader.getPageSize(FRONT_PAGE); retval = writer.getDirectContent(); // under = writer.getDirectContentUnder(); if (pageNumber.getInt() > FRONT_PAGE) { newPage = writer.getImportedPage(reader, CHECK_PAGE_NORMAL); setCurrentRenderingYPosition(pageSize.top(TOP_MARGIN + CHECK_DETAIL_HEADING_HEIGHT)); } else { newPage = writer.getImportedPage(reader, FRONT_PAGE); setCurrentRenderingYPosition(pageSize.top(TOP_FIRST_PAGE)); } pdfDoc = retval.getPdfDocument(); pdfDoc.newPage(); retval.addTemplate(newPage, 0, 0); retval.setFontAndSize(getTextFont(), 8); return retval; }
Example 7
Source File: ActionsTest.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
/** * Creates a document with some goto actions. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); Document remote = new Document(); // step 2: PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Actions.pdf")); PdfWriter.getInstance(remote, PdfTestBase.getOutputStream("remote.pdf")); // step 3: document.open(); remote.open(); // step 4: we add some content PdfAction action = PdfAction.gotoLocalPage(2, new PdfDestination(PdfDestination.XYZ, -1, 10000, 0), writer); writer.setOpenAction(action); document.add(new Paragraph("Page 1")); document.newPage(); document.add(new Paragraph("Page 2")); document.add(new Chunk("goto page 1").setAction(PdfAction.gotoLocalPage(1, new PdfDestination( PdfDestination.FITH, 500), writer))); document.add(Chunk.NEWLINE); document.add(new Chunk("goto another document").setAction(PdfAction.gotoRemotePage("remote.pdf", "test", false, true))); remote.add(new Paragraph("Some remote document")); remote.newPage(); Paragraph p = new Paragraph("This paragraph contains a "); p.add(new Chunk("local destination").setLocalDestination("test")); remote.add(p); // step 5: we close the document document.close(); remote.close(); }
Example 8
Source File: PdfReaderTest.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
@Ignore("validity of test needs to be resolved") @Test public void testGetLink() throws Exception { PdfReader currentReader = new PdfReader(PdfTestBase.RESOURCES_DIR +"getLinkTest1.pdf"); Document document = new Document(PageSize.A4, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new ByteArrayOutputStream()); document.open(); document.newPage(); List<?> links = currentReader.getLinks(1); PdfAnnotation.PdfImportedLink link = (PdfAnnotation.PdfImportedLink) links.get(0); writer.addAnnotation(link.createAnnotation(writer)); document.close(); }
Example 9
Source File: VerticalTest.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
/** * Writing vertical text. */ @Test public void main() throws Exception { Document document = new Document(PageSize.A4, 50, 50, 50, 50); texts[3] = convertCid(texts[0]); texts[4] = convertCid(texts[1]); texts[5] = convertCid(texts[2]); PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("vertical.pdf")); int idx = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); for (int j = 0; j < 2; ++j) { BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false); cb.setRGBColorStroke(255, 0, 0); cb.setLineWidth(0); float x = 400; float y = 700; float height = 400; float leading = 30; int maxLines = 6; for (int k = 0; k < maxLines; ++k) { cb.moveTo(x - k * leading, y); cb.lineTo(x - k * leading, y - height); } cb.rectangle(x, y, -leading * (maxLines - 1), -height); cb.stroke(); VerticalText vt = new VerticalText(cb); vt.setVerticalLayout(x, y, height, maxLines, leading); vt.addText(new Chunk(texts[idx++], new Font(bf, 20))); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue))); vt.go(); vt.setAlignment(Element.ALIGN_RIGHT); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange))); vt.go(); document.newPage(); } document.close(); }
Example 10
Source File: NamedActionsTest.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
/** * Creates a document with Named Actions. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2: we create a writer that listens to the document PdfWriter.getInstance(document, PdfTestBase.getOutputStream("NamedActions.pdf")); // step 3: we open the document document.open(); // step 4: we add some content Paragraph p = new Paragraph(new Chunk("Click to print").setAction(new PdfAction(PdfAction.PRINTDIALOG))); PdfPTable table = new PdfPTable(4); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(new Phrase(new Chunk("First Page").setAction(new PdfAction(PdfAction.FIRSTPAGE)))); table.addCell(new Phrase(new Chunk("Prev Page").setAction(new PdfAction(PdfAction.PREVPAGE)))); table.addCell(new Phrase(new Chunk("Next Page").setAction(new PdfAction(PdfAction.NEXTPAGE)))); table.addCell(new Phrase(new Chunk("Last Page").setAction(new PdfAction(PdfAction.LASTPAGE)))); for (int k = 1; k <= 10; ++k) { document.add(new Paragraph("This is page " + k)); document.add(Chunk.NEWLINE); document.add(table); document.add(p); document.newPage(); } // step 5: we close the document document.close(); }
Example 11
Source File: RemoteGotoTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Creates documents with Remote Goto functionality. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: PdfWriter writerA = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("DocumentA.pdf")); PdfWriter writerB = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("DocumentB.pdf")); // step 3: we open the document document.open(); // step 4: // we create some content // a paragraph with a link to an external url Paragraph p1 = new Paragraph("You can turn a Chunk into an ", FontFactory.getFont(FontFactory.HELVETICA, 12)); p1.add(new Chunk("anchor", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, new Color(0, 0, 255))) .setAnchor(new URL("http://www.lowagie.com/iText/"))); p1.add(", for instance to the iText site."); // some paragraph Paragraph p2 = new Paragraph("blah, blah, blah"); // two paragraphs with a local destination Paragraph p3a = new Paragraph("This paragraph contains a "); p3a.add(new Chunk("local destination in document A", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 255, 0))).setLocalDestination("test")); Paragraph p3b = new Paragraph("This paragraph contains a "); p3b.add(new Chunk("local destination in document B", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 255, 0))).setLocalDestination("test")); // two paragraphs with a remote goto Paragraph p4a = new Paragraph( new Chunk("Click this paragraph to go to a certain destination on document B").setRemoteGoto( "DocumentB.pdf", "test")); Paragraph p4b = new Paragraph( new Chunk("Click this paragraph to go to a certain destination on document A").setRemoteGoto( "DocumentA.pdf", "test")); // a special remote goto Paragraph p5a = new Paragraph("you can also jump to a "); p5a.add(new Chunk("specific page on another document", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.ITALIC)).setRemoteGoto("DocumentB.pdf", 3)); // we add all the content document.add(p1); document.add(p2); document.add(p2); document.add(p2); document.add(p2); document.add(p2); document.add(p2); document.add(p2); // only for DocumentB.pdf: writerA.pause(); document.add(p4b); writerA.resume(); // only for DocumentA.pdf: writerB.pause(); document.add(p4a); document.add(p5a); writerB.resume(); // for both documents: document.add(p2); document.add(p2); document.add(p2); document.add(p2); // only for DocumentB.pdf: writerA.pause(); document.add(p3b); document.add(p2); document.add(p2); document.newPage(); document.add(p2); document.add(p2); document.newPage(); writerA.resume(); // only for documentA.pdf writerB.pause(); document.add(p3a); writerB.resume(); // for both documents document.add(p2); document.add(p2); // step 5: we close the document document.close(); }
Example 12
Source File: FancyListsTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Demonstrates some List functionality. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: PdfWriter.getInstance(document, PdfTestBase.getOutputStream("fancylists.pdf")); // step 3: we open the document document.open(); // step 4: // RomanList RomanList roman = new RomanList(35); roman.setLowercase(true); roman.add(new ListItem("first item")); roman.add(new ListItem( "second item blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah")); for (int i = 3; i < 151; i++) { roman.add(i + "th item"); } document.add(roman); document.newPage(); RomanList roman2 = new RomanList(35); roman2.add(new ListItem("first item")); roman2.add(new ListItem("second item")); for (int i = 3; i < 11; i++) { roman2.add(i + "th item"); } document.add(roman2); document.newPage(); // GreekList GreekList greek = new GreekList(15); greek.setLowercase(true); greek.add(new ListItem("first item")); greek.add(new ListItem("second item")); for (int i = 3; i < 20; i++) { greek.add(i + "th item"); } document.add(greek); document.newPage(); // GreekList GreekList greek2 = new GreekList(15); greek2.setLowercase(false); greek2.add(new ListItem("first item")); greek2.add(new ListItem("second item")); for (int i = 3; i < 20; i++) { greek2.add(i + "th item"); } document.add(greek2); // ZapfDingbatsList ZapfDingbatsList z = new ZapfDingbatsList(42, 15); z.add(new ListItem("first item")); z.add(new ListItem("second item")); for (int i = 3; i < 20; i++) { z.add(i + "th item"); } document.add(z); document.newPage(); // ZapfDingbatsNumberList ZapfDingbatsNumberList z0 = new ZapfDingbatsNumberList(0, 15); z0.add(new ListItem("first item")); z0.add(new ListItem("second item")); for (int i = 3; i < 11; i++) { z0.add(i + "th item"); } document.add(z0); ZapfDingbatsNumberList z1 = new ZapfDingbatsNumberList(1, 15); z1.add(new ListItem("first item")); z1.add(new ListItem("second item")); for (int i = 3; i < 11; i++) { z1.add(i + "th item"); } document.add(z1); ZapfDingbatsNumberList z2 = new ZapfDingbatsNumberList(2, 15); z2.add(new ListItem("first item")); z2.add(new ListItem("second item")); for (int i = 3; i < 11; i++) { z2.add(i + "th item"); } document.add(z2); ZapfDingbatsNumberList z3 = new ZapfDingbatsNumberList(3, 15); z3.add(new ListItem("first item")); z3.add(new ListItem("second item")); for (int i = 3; i < 11; i++) { z3.add(i + "th item"); } document.add(z3); // step 5: we close the document document.close(); }
Example 13
Source File: SimpleAnnotationsTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Creates documents with some simple annotations. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document1 = new Document(PageSize.A4, 10, 10, 10, 10); Document document2 = new Document(PageSize.A4, 10, 10, 10, 10); // step 2: PdfWriter writer1 = PdfWriter.getInstance(document1, PdfTestBase.getOutputStream("SimpleAnnotations1.pdf")); PdfWriter writer2 = PdfWriter.getInstance(document2, PdfTestBase.getOutputStream("SimpleAnnotations2.pdf")); // step 3: writer2.setPdfVersion(PdfWriter.VERSION_1_5); document1.open(); document2.open(); // step 4: document1.add(new Paragraph("Each square on this page represents an annotation.")); // document1 PdfContentByte cb1 = writer1.getDirectContent(); Annotation a1 = new Annotation("authors", "Maybe it's because I wanted to be an author myself that I wrote iText.", 250f, 700f, 350f, 800f); document1.add(a1); Annotation a2 = new Annotation(250f, 550f, 350f, 650f, new URL("http://www.lowagie.com/iText/")); document1.add(a2); Annotation a3 = new Annotation(250f, 400f, 350f, 500f, "http://www.lowagie.com/iText"); document1.add(a3); Image image = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.gif"); image.setAnnotation(a3); document1.add(image); Annotation a4 = new Annotation(250f, 250f, 350f, 350f, PdfAction.LASTPAGE); document1.add(a4); // draw rectangles to show where the annotations were added cb1.rectangle(250, 700, 100, 100); cb1.rectangle(250, 550, 100, 100); cb1.rectangle(250, 400, 100, 100); cb1.rectangle(250, 250, 100, 100); cb1.stroke(); // more content document1.newPage(); for (int i = 0; i < 5; i++) { document1.add(new Paragraph("blahblahblah")); } document1.add(new Annotation("blahblah", "Adding an annotation without specifying coordinates")); for (int i = 0; i < 3; i++) { document1.add(new Paragraph("blahblahblah")); } document1.newPage(); document1.add(new Chunk("marked chunk").setLocalDestination("mark")); File videoFile = new File(PdfTestBase.RESOURCES_DIR + "cards.mpg"); File license = new File("LICENSE"); // document2 document2.add(new Paragraph("Each square on this page represents an annotation.")); PdfContentByte cb2 = writer2.getDirectContent(); Annotation a5 = new Annotation(100f, 700f, 200f, 800f, videoFile.getAbsolutePath(), "video/mpeg", true); document2.add(a5); Annotation a6 = new Annotation(100f, 550f, 200f, 650f, "SimpleAnnotations1.pdf", "mark"); document2.add(a6); Annotation a7 = new Annotation(100f, 400f, 200f, 500f, "SimpleAnnotations1.pdf", 2); document2.add(a7); Annotation a8 = new Annotation(100f, 250f, 200f, 350f, license.getAbsolutePath(), null, null, null); document2.add(a8); // draw rectangles to show where the annotations were added cb2.rectangle(100, 700, 100, 100); cb2.rectangle(100, 550, 100, 100); cb2.rectangle(100, 400, 100, 100); cb2.rectangle(100, 250, 100, 100); cb2.stroke(); // step 5: we close the document document1.close(); document2.close(); }
Example 14
Source File: SplitPdf.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * This class can be used to split an existing PDF file. * @param args the command line arguments */ public static void main(String args[]) { if (args.length != 4) { System.err.println("arguments: srcfile destfile1 destfile2 pagenumber"); } else { try { int pagenumber = Integer.parseInt(args[3]); // we create a reader for a certain document PdfReader reader = new PdfReader(args[0]); // we retrieve the total number of pages int n = reader.getNumberOfPages(); System.out.println("There are " + n + " pages in the original file."); if (pagenumber < 2 || pagenumber > n) { throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page."); } // step 1: creation of a document-object Document document1 = new Document(reader.getPageSizeWithRotation(1)); Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber)); // step 2: we create a writer that listens to the document PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1])); PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2])); // step 3: we open the document document1.open(); PdfContentByte cb1 = writer1.getDirectContent(); document2.open(); PdfContentByte cb2 = writer2.getDirectContent(); PdfImportedPage page; int rotation; int i = 0; // step 4: we add content while (i < pagenumber - 1) { i++; document1.setPageSize(reader.getPageSizeWithRotation(i)); document1.newPage(); page = writer1.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); } else { cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } while (i < n) { i++; document2.setPageSize(reader.getPageSizeWithRotation(i)); document2.newPage(); page = writer2.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); } else { cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } System.out.println("Processed page " + i); } // step 5: we close the document document1.close(); document2.close(); } catch(Exception e) { e.printStackTrace(); } } }
Example 15
Source File: PaperightPdfConverter.java From website with GNU Affero General Public License v3.0 | 4 votes |
private String createOneUp(String originalPdfFile) throws IOException, DocumentException { logger.debug("Started create 1-up file from " + originalPdfFile); String filename = FilenameUtils.getBaseName(originalPdfFile) + "_1up." + FilenameUtils.getExtension(originalPdfFile); String tempFilename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp"); filename = FilenameUtils.concat(getPdfFileFolder(), filename); File tempFile = new File(tempFilename); //float scale = 0.80f; PdfReader reader = new PdfReader(originalPdfFile); Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //Document doc = new Document(new RectangleReadOnly(606.96f, 850.32f), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile)); doc.open(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { doc.newPage(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page = writer.getImportedPage(reader, i); float documentWidth = doc.getPageSize().getWidth(); float documentHeight = doc.getPageSize().getHeight(); if (i > 1) { documentHeight = documentHeight - 65f; } /*float documentHeight = doc.getPageSize().getHeight(); if (i > 1) { documentHeight = documentHeight - 65f; } float documentWidth = doc.getPageSize().getWidth();*/ float pageWidth = page.getWidth(); float pageHeight = page.getHeight(); float widthScale = documentWidth / pageWidth; float heightScale = documentHeight / pageHeight; float scale = Math.min(widthScale, heightScale); float offsetX = (documentWidth - (pageWidth * scale)) / 2; float offsetY = 0f; if (i > 1) { offsetY = 65f; } /* float offsetX = 0f; if (i > 1) { offsetX = 65f; //100f } //float offsetX = 65f; float offsetY = ((documentHeight) - (pageHeight * scale)) / 2;*/ cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY); } doc.close(); overlayLicenceArea(tempFilename, filename, PageLayout.ONE_UP); logger.debug("Deleting temporary file " + tempFile.getAbsolutePath()); FileUtils.deleteQuietly(tempFile); logger.debug("Completed create 1-up file from " + originalPdfFile); return filename; }
Example 16
Source File: PaperightPdfConverter.java From website with GNU Affero General Public License v3.0 | 4 votes |
private String createA5(String originalPdfFile) throws IOException, DocumentException { logger.debug("Started create A5 file from " + originalPdfFile); String filename = FilenameUtils.getBaseName(originalPdfFile) + "_a5." + FilenameUtils.getExtension(originalPdfFile); String tempFilename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp"); filename = FilenameUtils.concat(getPdfFileFolder(), filename); File tempFile = new File(tempFilename); //float scale = 0.72906403940886699507389162561576f; PdfReader reader = new PdfReader(originalPdfFile); //new RectangleReadOnly(425.16f, 606.96f) Document doc = new Document(PageSize.A5, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile)); doc.open(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { doc.newPage(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page = writer.getImportedPage(reader, i); // page #1 float documentWidth = doc.getPageSize().getWidth(); float documentHeight = doc.getPageSize().getHeight(); if (i > 1) { documentHeight = documentHeight - 65f; } //float documentHeight = doc.getPageSize().getHeight() - 65f; float pageWidth = page.getWidth(); float pageHeight = page.getHeight(); float widthScale = documentWidth / pageWidth; float heightScale = documentHeight / pageHeight; float scale = Math.min(widthScale, heightScale); //float offsetX = 50f; float offsetX = (documentWidth - (pageWidth * scale)) / 2; float offsetY = 0f; if (i > 1) { offsetY = 65f; } //float offsetY = ((documentHeight) - (pageHeight * scale)) / 2; cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY); //cb.addTemplate(page, scale, 0, 0, scale, 50f, 100f); } doc.close(); //FileUtils.moveFile(tempFile, new File(filename)); overlayLicenceArea(tempFilename, filename, PageLayout.A5); logger.debug("Deleting temporary file " + tempFile.getAbsolutePath()); FileUtils.deleteQuietly(tempFile); logger.debug("Completed create A5 file from " + originalPdfFile); return filename; }
Example 17
Source File: RepeatingTableTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Shows how a table is split if it doesn't fit the page. */ @Test public void main() throws Exception { // creation of the document with a certain size and certain margins Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50); // creation of the different writers PdfWriter.getInstance(document, PdfTestBase.getOutputStream("repeatingtable.pdf")); // we add some meta information to the document document.addAuthor("Alan Soukup"); document.addSubject("This is the result of a Test."); document.open(); Table datatable = new Table(10); int headerwidths[] = { 10, 24, 12, 12, 7, 7, 7, 7, 7, 7 }; datatable.setWidths(headerwidths); datatable.setWidth(100); datatable.setPadding(3); // the first cell spans 10 columns Cell cell = new Cell(new Phrase("Administration -System Users Report", FontFactory.getFont( FontFactory.HELVETICA, 24, Font.BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setLeading(30); cell.setColspan(10); cell.setBorder(Rectangle.NO_BORDER); cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0)); datatable.addCell(cell); // These cells span 2 rows datatable.getDefaultCell().setBorderWidth(2); datatable.getDefaultCell().setHorizontalAlignment(1); datatable.addCell("User Id"); datatable.addCell("Name\nAddress"); datatable.addCell("Company"); datatable.addCell("Department"); datatable.addCell("Admin"); datatable.addCell("Data"); datatable.addCell("Expl"); datatable.addCell("Prod"); datatable.addCell("Proj"); datatable.addCell("Online"); // this is the end of the table header datatable.endHeaders(); datatable.getDefaultCell().setBorderWidth(1); for (int i = 1; i < 30; i++) { datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); datatable.addCell("myUserId"); datatable .addCell("Somebody with a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long name"); datatable.addCell("No Name Company"); datatable.addCell("D" + i); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); datatable.addCell("No"); datatable.addCell("Yes"); datatable.addCell("No"); datatable.addCell("Yes"); datatable.addCell("No"); datatable.addCell("Yes"); } document.add(new Paragraph("com.lowagie.text.Table - Cells split")); document.add(datatable); document.newPage(); document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells split\n\n")); datatable.setConvert2pdfptable(true); document.add(datatable); document.newPage(); document.add(new Paragraph("com.lowagie.text.Table - Cells kept together")); datatable.setConvert2pdfptable(false); datatable.setCellsFitPage(true); document.add(datatable); document.newPage(); document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells kept together\n\n")); datatable.setConvert2pdfptable(true); document.add(datatable); // we close the document document.close(); }
Example 18
Source File: ParagraphAttributesTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Demonstrates some Paragraph functionality. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document PdfWriter.getInstance(document, PdfTestBase.getOutputStream("ParagraphAttributes.pdf")); // step 3: we open the document document.open(); // step 4: Paragraph[] p = new Paragraph[5]; p[0] = new Paragraph( "GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur. Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt. Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt."); p[1] = new Paragraph( "[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]"); p[2] = new Paragraph( "Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix. Is M. Messala, [et P.] M. Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent: perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri. Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur: una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit. His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur. Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant."); p[3] = new Paragraph( "His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare. Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant. Ad eas res conficiendas Orgetorix deligitur. Is sibi legationem ad civitates suscipit. In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat. Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset: non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat. Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant."); p[4] = new Paragraph( "Ea res est Helvetiis per indicium enuntiata. Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur. Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit. Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit."); for (int i = 0; i < 5; i++) { p[i].setAlignment(Element.ALIGN_JUSTIFIED); document.add(p[i]); } document.newPage(); for (int i = 0; i < 5; i++) { p[i].setAlignment(Element.ALIGN_JUSTIFIED); p[i].setIndentationLeft(i * 15f); p[i].setIndentationRight((5 - i) * 15f); document.add(p[i]); } document.newPage(); for (int i = 0; i < 5; i++) { p[i].setAlignment(Element.ALIGN_RIGHT); p[i].setSpacingAfter(15f); document.add(p[i]); } for (int i = 0; i < 5; i++) { p[i].setAlignment(Element.ALIGN_LEFT); p[i].setSpacingBefore(15f); document.add(p[i]); } for (int i = 0; i < 5; i++) { p[i].setAlignment(Element.ALIGN_CENTER); p[i].setSpacingAfter(15f); p[i].setSpacingBefore(15f); document.add(p[i]); } document.newPage(); // step 5: we close the document document.close(); }
Example 19
Source File: GlossaryTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Generic page event. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Glossary.pdf")); GlossaryTest generic = new GlossaryTest(); writer.setPageEvent(generic); // step 3: we open the document document.open(); // step 4: String[] f = new String[14]; f[0] = "Courier"; f[1] = "Courier Bold"; f[2] = "Courier Italic"; f[3] = "Courier Bold Italic"; f[4] = "Helvetica"; f[5] = "Helvetica bold"; f[6] = "Helvetica italic"; f[7] = "Helvetica bold italic"; f[8] = "Times New Roman"; f[9] = "Times New Roman bold"; f[10] = "Times New Roman italic"; f[11] = "Times New Roman bold italic"; f[12] = "Symbol"; f[13] = "Zapfdingbats"; Font[] fonts = new Font[14]; fonts[0] = FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL); fonts[1] = FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD); fonts[2] = FontFactory.getFont(FontFactory.COURIER, 12, Font.ITALIC); fonts[3] = FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD | Font.ITALIC); fonts[4] = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL); fonts[5] = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD); fonts[6] = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.ITALIC); fonts[7] = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD | Font.ITALIC); fonts[8] = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL); fonts[9] = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD); fonts[10] = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.ITALIC); fonts[11] = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD | Font.ITALIC); fonts[12] = FontFactory.getFont(FontFactory.SYMBOL, 12, Font.NORMAL); fonts[13] = FontFactory.getFont(FontFactory.ZAPFDINGBATS, 12, Font.NORMAL); for (int i = 0; i < 14; i++) { Chunk chunk = new Chunk("This is font ", fonts[i]); Paragraph p = new Paragraph(chunk); p.add(new Phrase(new Chunk(f[i], fonts[i]).setGenericTag(f[i]))); document.add(p); if (i % 4 == 3) { document.newPage(); } } // we add the glossary document.newPage(); for (Iterator<String> i = generic.glossary.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); int page = ((Integer) generic.glossary.get(key)).intValue(); Paragraph g = new Paragraph(key); g.add(" : page "); g.add(String.valueOf(page)); document.add(g); } // step 5: we close the document document.close(); }
Example 20
Source File: EpubToPdfConverter.java From website with GNU Affero General Public License v3.0 | 4 votes |
public File convert(String epubPath) throws IOException,DocumentException { applyProperties(epub2pdfProps); File epubFile = new File(epubPath); if (!(epubFile.canRead())) { throw new IOException("Could not read " + epubPath); } else { logger.debug("Converting " + epubFile.getAbsolutePath()); } String epubFilename = epubFile.getName(); String epubFilenameBase = epubFilename.substring(0, epubFilename.length()-5); String pdfFilename = epubFilenameBase + ".pdf"; File outputFile = new File(outputDir.getAbsolutePath() + File.separator + pdfFilename); epubIn = Epub.fromFile(epubPath); XhtmlHandler.setSourceEpub(epubIn); Opf opf = epubIn.getOpf(); List<String> contentPaths = opf.spineHrefs(); List<File> contentFiles = new ArrayList<File>(); for (String path : contentPaths) { contentFiles.add(new File(epubIn.getContentRoot(),path)); } Ncx ncx = epubIn.getNcx(); List<NavPoint> ncxToc = new ArrayList<NavPoint>(); if(ncx != null) { ncxToc.addAll(ncx.getNavPointsFlat()); } Tree<TocTreeNode> tocTree = TocTreeNode.buildTocTree(ncx); XhtmlHandler.setTocTree(tocTree); Document doc = new Document(); boolean pageSizeOK = doc.setPageSize(pageSize); boolean marginsOK = doc.setMargins(marginLeftPt, marginRightPt, marginTopPt, marginBottomPt); logger.debug("Writing PDF to " + outputFile.getAbsolutePath()); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outputFile)); writer.setStrictImageSequence(true); PdfOutline bookmarkRoot = null; if (!(pageSizeOK && marginsOK)) { throw new RuntimeException("Failed to set PDF page size a/o margins"); } int fileCount = contentFiles.size(); logger.debug("Processing " + fileCount + " HTML file(s): "); int currentFile = 0; for (File file : contentFiles) { currentFile++; String progressChar; int mod10 = currentFile % 10; if(mod10 == 5) progressChar = "5"; else if(mod10 == 0) progressChar = "0"; else progressChar = "."; logger.debug(progressChar); if (!(doc.isOpen())) { doc.open(); doc.newPage(); bookmarkRoot = writer.getRootOutline(); XhtmlHandler.setBookmarkRoot(bookmarkRoot); } NavPoint fileLevelNP = Ncx.findNavPoint(ncxToc, file.getName()); TreeNode<TocTreeNode> npNode = TocTreeNode.findInTreeByNavPoint(tocTree, fileLevelNP); if(fileLevelNP != null) { doc.newPage(); PdfOutline pdfOutlineParent = bookmarkRoot; if(npNode != null) { TreeNode<TocTreeNode> parent = npNode.getParent(); if(parent != null) { TocTreeNode parentTTN = parent.getValue(); if(parentTTN != null && parentTTN.getPdfOutline() != null) { pdfOutlineParent = parentTTN.getPdfOutline(); } } } PdfDestination here = new PdfDestination(PdfDestination.FIT); PdfOutline pdfTocEntry = new PdfOutline(pdfOutlineParent, here, fileLevelNP.getNavLabelText()); if(npNode != null) { npNode.getValue().setPdfDestination(here); npNode.getValue().setPdfOutline(pdfTocEntry); } } XhtmlHandler.process(file.getCanonicalPath(), doc); } doc.close(); logger.debug("PDF written to " + outputFile.getAbsolutePath()); epubIn.cleanup(); return outputFile; }