@Override public void onEndPage(PdfWriter writer, Document document) { Phrase[] headers = new Phrase[3]; PdfContentByte cb = writer.getDirectContent(); headers[0] = new Phrase("CuacFM"); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, headers[0], document.left() + 80, document.bottom() - 20, 0); Date day = new Date(); headers[1] = new Phrase(DateUtils.format(day, DateUtils.FORMAT_LOCAL)); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, headers[1], (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 20, 0); headers[2] = new Phrase(String.format("Página %d", writer.getCurrentPageNumber())); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, headers[2], document.right() - 80, document.bottom() - 20, 0); }
protected void writePageAnchor(int pageIndex) throws DocumentException { Map<Attribute,Object> attributes = new HashMap<Attribute,Object>(); fontUtil.getAttributesWithoutAwtFont(attributes, new JRBasePrintText(jasperPrint.getDefaultStyleProvider())); Font pdfFont = getFont(attributes, getLocale(), false); Chunk chunk = new Chunk(" ", pdfFont); chunk.setLocalDestination(JR_PAGE_ANCHOR_PREFIX + reportIndex + "_" + (pageIndex + 1)); tagHelper.startPageAnchor(); ColumnText colText = new ColumnText(pdfContentByte); colText.setSimpleColumn( new Phrase(chunk), 0, pageFormat.getPageHeight(), 1, 1, 0, Element.ALIGN_LEFT ); colText.go(); tagHelper.endPageAnchor(); }
private boolean breakPage(boolean pageBreak, float upperYcoord) { if( pageBreak ) { ColumnText.showTextAligned(cb, Phrase.ALIGN_CENTER, new Phrase("-" + curPage + "-"), document.right()/2f, document.bottom()-(document.bottomMargin()/2f), 0f); ++curPage; try{ document.newPage(); // add promo text to new page addPromoText(); }catch(Exception e){} if( curPage == numPages ) { maxLines = (numLines - totalLinesWritten) / NUMCOLS; } ct.setSimpleColumn(document.left(), document.bottom(), document.right()/2f, upperYcoord); pageBreak = false; } else { ct.setSimpleColumn(document.right()/2f, document.bottom(), document.right(), upperYcoord); pageBreak = true; } return pageBreak; }
private boolean checkColumnFill(ColumnText ct, String preventionHeader, Font font, boolean pageBreak) { if( linesWritten + linesToBeWritten > maxLines ) { //reset upperYcoord for pages 2 and above if( curPage == 1 && pageBreak) { upperYcoord = document.top() - font.getCalculatedLeading(LINESPACING); pageHeight = upperYcoord - document.bottom(); maxLines = (int)Math.floor(pageHeight/(font.getCalculatedLeading(LINESPACING)+4d)); numPages = (int)Math.ceil(((double)numLines-totalLinesWritten)/((double)maxLines*NUMCOLS)) + 1; } pageBreak = breakPage(pageBreak, upperYcoord); linesWritten = 0; if( preventionHeader.length() > 0 ) { Phrase procHeaderContd = new Phrase(LEADING, "Prevention " + preventionHeader + " cont'd\n", font); ct.addText(procHeaderContd); ++linesToBeWritten; } } return pageBreak; }
/** * Demonstrates some Layer 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("Layers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseOC); document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer grouping", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); PdfArray group = new PdfArray(); group.add(new PdfString("A group of two", PdfObject.TEXT_UNICODE)); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5: we close the document document.close(); }
@Override public void render() { ColumnText colText = new ColumnText(pdfContentByte); colText.setSimpleColumn( getPhrase(styledText, text), x + leftPadding, pdfExporter.getCurrentPageFormat().getPageHeight() - y - topPadding - verticalAlignOffset - text.getLeadingOffset(), //+ text.getLineSpacingFactor() * text.getFont().getSize(), x + width - rightPadding, pdfExporter.getCurrentPageFormat().getPageHeight() - y - height + bottomPadding, 0,//text.getLineSpacingFactor(),// * text.getFont().getSize(), horizontalAlignment == Element.ALIGN_JUSTIFIED_ALL ? Element.ALIGN_JUSTIFIED : horizontalAlignment ); colText.setLeading(0, text.getLineSpacingFactor());// * text.getFont().getSize()); colText.setRunDirection( text.getRunDirectionValue() == RunDirectionEnum.LTR ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_RTL ); try { colText.go(); } catch (DocumentException e) { throw new JRRuntimeException(e); } }
private void addHeaderAndFooter(PdfWriter writer, Document document) { if (document.getPageNumber() == 1) { return; } String header = docInstallArgs.getDocName() + " version" + docInstallArgs.getVersion(); PdfContentByte directContent = writer.getDirectContent(); Phrase headerPhare = ItextUtil.getFontSelector(9, Font.NORMAL, Color.LIGHT_GRAY).process(header); headerPhare.add(new LineSeparator(0.5f, 2.5f, Color.LIGHT_GRAY, Element.ALIGN_LEFT, -5f)); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, headerPhare, document.left(), document.top() + 20, 0); String footer = Integer.valueOf(document.getPageNumber()).toString(); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, textbFont.process(footer), document.getPageSize().getWidth() / 2.0f - 20, document.bottom() - 20, 0); }
/** * Demonstrates how to group optional content. * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Grouping optional content"); try { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "contentgroups.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer grouping", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.sanityCheck(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); PdfArray group = new PdfArray(); group.add(new PdfString("A group of two", PdfObject.TEXT_UNICODE)); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
/** * Demonstrates how to order optional content groups. * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Ordering optional content groups"); try { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "orderedlayers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Ordered layers", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.sanityCheck(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); order.add(l2.getRef()); order.add(l3.getRef()); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
/** * Demonstrates how to order optional content groups. * * @param args * no arguments needed */ @Test public void main() throws Exception { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("orderedlayers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Ordered layers", new Font( Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.sanityCheck(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); order.add(l2.getRef()); order.add(l3.getRef()); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5 document.close(); }
/** * Demonstrates the use of layers. * * @param args * no arguments needed */ @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: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("optionalcontent.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3: opening the document document.open(); // step 4: content PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase( "Automatic layers, form fields, images, templates and actions", new Font(Font.HELVETICA, 18, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayer l4 = new PdfLayer("Form and XObject Layer", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0f); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); TextField ff = new TextField(writer, new Rectangle(200, 600, 300, 620), "field1"); ff.setBorderColor(Color.blue); ff.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); ff.setBorderWidth(TextField.BORDER_WIDTH_THIN); ff.setText("I'm a form field"); PdfFormField form = ff.getTextField(); form.setLayer(l4); writer.addAnnotation(form); Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR + "pngnow.png"); img.setLayer(l4); img.setAbsolutePosition(200, 550); cb.addImage(img); PdfTemplate tp = cb.createTemplate(100, 20); Phrase pt = new Phrase("I'm a template", new Font(Font.HELVETICA, 12, Font.NORMAL, Color.magenta)); ColumnText.showTextAligned(tp, Element.ALIGN_LEFT, pt, 0, 0, 0); tp.setLayer(l4); tp.setBoundingBox(new Rectangle(0, -10, 100, 20)); cb.addTemplate(tp, 200, 500); ArrayList<Object> state = new ArrayList<Object>(); state.add("toggle"); state.add(l1); state.add(l2); state.add(l3); state.add(l4); PdfAction action = PdfAction.setOCGstate(state, true); Chunk ck = new Chunk("Click here to toggle the layers", new Font( Font.HELVETICA, 18, Font.NORMAL, Color.yellow)).setBackground( Color.blue).setAction(action); ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(ck), 250, 400, 0); cb.sanityCheck(); // step 5: closing the document document.close(); }
/** * Layer radio group and zoom. */ @Test public void main() throws Exception { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "layers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer radio group and zoom", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer title = PdfLayer.createTitle("Layer radio group", writer); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayer l4 = new PdfLayer("Layer 4", writer); title.addChild(l1); title.addChild(l2); title.addChild(l3); l4.setZoom(2, -1); l4.setOnPanel(false); l4.setPrint("Print", true); l2.setOn(false); l3.setOn(false); ArrayList<PdfLayer> radio = new ArrayList<PdfLayer>(); radio.add(l1); radio.add(l2); radio.add(l3); writer.addOCGRadioGroup(radio); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2"); Phrase p3 = new Phrase("Text in layer 3"); Phrase p4 = new Phrase("Text in layer 4"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(l2); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.beginLayer(l4); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p4, 50, 450, 0); cb.endLayer(); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("<< Zoom here!", new Font(Font.COURIER, 12, Font.NORMAL, Color.blue)), 150, 450, 0); // step 5 document.close(); }
/** * Automatic grouping and nesting. */ @Test public void main() throws Exception { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("automatic.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Automatic layer grouping and nesting", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l12 = new PdfLayer("Layer nesting", writer); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer title = PdfLayer.createTitle("Layer grouping", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayer l4 = new PdfLayer("Layer 4", writer); l12.addChild(l1); l12.addChild(l2); title.addChild(l3); title.addChild(l4); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2"); Phrase p3 = new Phrase("Text in layer 3"); Phrase p4 = new Phrase("Text in layer 4"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(l2); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.beginLayer(l4); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p4, 50, 450, 0); cb.endLayer(); cb.sanityCheck(); // step 5 document.close(); }
/** * Demonstrates the use of nested layers * * @param args * no arguments needed */ @Test public void main() throws Exception { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("nestedlayers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer nesting", new Font( Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l23 = new PdfLayer("Top Layer 2 3", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(l23); cb.beginLayer(l2); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.endLayer(); cb.sanityCheck(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); order.add(l23.getRef()); PdfArray group = new PdfArray(); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5 document.close(); }
/** * Demonstrates how to group optional content. */ @Test public void main() throws Exception { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "contentgroups.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer grouping", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.sanityCheck(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); PdfArray group = new PdfArray(); group.add(new PdfString("A group of two", PdfObject.TEXT_UNICODE)); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5 document.close(); }
/** * Adding text at absolute positions. * * @param args * no arguments needed */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("complextext.pdf")); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); // first we draw some lines to be able to visualize the text alignment // functions cb.setLineWidth(0f); cb.moveTo(250, 500); cb.lineTo(250, 800); cb.moveTo(50, 700); cb.lineTo(400, 700); cb.moveTo(50, 650); cb.lineTo(400, 650); cb.moveTo(50, 600); cb.lineTo(400, 600); cb.stroke(); File font = new File (PdfTestBase.RESOURCES_DIR + "/liberation-fonts-ttf/LiberationSans-Regular.ttf"); // we construct a font BaseFont bf = BaseFont.createFont(font.getAbsolutePath(), BaseFont.IDENTITY_H, true); Font ft = new Font(bf, 12); // This is the text: String text = "\u0623\u0648\u0631\u0648\u0628\u0627, \u0628\u0631\u0645\u062c\u064a\u0627\u062a \u0627\u0644\u062d\u0627\u0633\u0648\u0628 + \u0627\u0646\u062a\u0631\u0646\u064a\u062a :"; Phrase center = new Phrase(text + " Center", ft); ColumnText .showTextAligned(cb, PdfContentByte.ALIGN_CENTER, center, 250, 700, 0, PdfWriter.RUN_DIRECTION_RTL, 0); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_RIGHT, new Phrase(text + " Right", ft), 250, 650, 20, PdfWriter.RUN_DIRECTION_RTL, 0); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, new Phrase("Some text Left aligned", ft), 250, 600, 20); float size = ColumnText.getWidth(center, PdfWriter.RUN_DIRECTION_RTL, 0); cb.setRGBColorStroke(255, 0, 0); cb.rectangle(250 - size / 2, 690, size, 30); cb.stroke(); // step 5: we close the document document.close(); }
/** * Demonstrating the use of ColumnText */ @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 // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("columnsimple.pdf")); // step 3: we open the document document.open(); // step 4: // we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font font = new Font(bf, 11, Font.NORMAL); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(60, 300, 100, 300 + 28 * 15, 15, Element.ALIGN_CENTER); ct.addText(new Phrase(15, "UNI\n", font)); for (int i = 0; i < 27; i++) { ct.addText(new Phrase(15, uni[i] + "\n", font)); } ct.go(); cb.rectangle(103, 295, 52, 8 + 28 * 15); cb.stroke(); ct.setSimpleColumn(105, 300, 150, 300 + 28 * 15, 15, Element.ALIGN_RIGHT); ct.addText(new Phrase(15, "char\n", font)); for (int i = 0; i < 27; i++) { ct.addText(new Phrase(15, code[i] + "\n", font)); } ct.go(); ct.setSimpleColumn(160, 300, 500, 300 + 28 * 15, 15, Element.ALIGN_LEFT); ct.addText(new Phrase(15, "NAME" + "\n", font)); for (int i = 0; i < 27; i++) { ct.addText(new Phrase(15, name[i] + "\n", font)); } ct.go(); // step 5: we close the document document.close(); }
/** * Demonstrates the use of ColumnText. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("columnirregular.pdf")); // step 3: we open the document document.open(); // step 4: // we grab the contentbyte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); PdfTemplate t = cb.createTemplate(600, 800); Image caesar = Image.getInstance(PdfTestBase.RESOURCES_DIR + "caesar_coin.jpg"); cb.addImage(caesar, 100, 0, 0, 100, 260, 595); t.setGrayFill(0.75f); t.moveTo(310, 112); t.lineTo(280, 60); t.lineTo(340, 60); t.closePath(); t.moveTo(310, 790); t.lineTo(310, 710); t.moveTo(310, 580); t.lineTo(310, 122); t.stroke(); cb.addTemplate(t, 0, 0); ColumnText ct = new ColumnText(cb); ct.addText(new Phrase( "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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "[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.]\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "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.", FontFactory.getFont(FontFactory.HELVETICA, 12))); float[] left1 = { 70, 790, 70, 60 }; float[] right1 = { 300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60 }; float[] left2 = { 320, 790, 320, 700, 380, 700, 380, 590, 320, 590, 320, 106, 350, 60 }; float[] right2 = { 550, 790, 550, 60 }; int status = 0; int column = 0; while ((status & ColumnText.NO_MORE_TEXT) == 0) { if (column == 0) { ct.setColumns(left1, right1); column = 1; } else { ct.setColumns(left2, right2); column = 0; } status = ct.go(); ct.setYLine(790); ct.setAlignment(Element.ALIGN_JUSTIFIED); status = ct.go(); if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) { document.newPage(); cb.addTemplate(t, 0, 0); cb.addImage(caesar, 100, 0, 0, 100, 260, 595); } } // step 5: we close the document document.close(); }
/** * Demonstrating the use of ColumnText */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("column.pdf")); // step 3: we open the document document.open(); // step 4: // we create some content BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font font = new Font(bf, 11, Font.NORMAL); Phrase unicodes = new Phrase(15, "UNI\n", font); Phrase characters = new Phrase(15, "\n", font); Phrase names = new Phrase(15, "NAME\n", font); for (int i = 0; i < 27; i++) { unicodes.add(uni[i] + "\n"); characters.add(code[i] + "\n"); names.add(name[i] + "\n"); } // we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(unicodes, 60, 300, 100, 300 + 28 * 15, 15, Element.ALIGN_CENTER); ct.go(); cb.rectangle(103, 295, 52, 8 + 28 * 15); cb.stroke(); ct.setSimpleColumn(characters, 105, 300, 150, 300 + 28 * 15, 15, Element.ALIGN_RIGHT); ct.go(); ct.setSimpleColumn(names, 160, 300, 500, 300 + 28 * 15, 15, Element.ALIGN_LEFT); ct.go(); // step 5: we close the document document.close(); }
public void printPdf(LoggedInInfo loggedInInfo) throws IOException, DocumentException{ EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil(); reqForm.estRequestFromId(loggedInInfo, (String) request.getAttribute("reqId")); // init req form info reqForm.specAddr = request.getParameter("address"); if (reqForm.specAddr == null){reqForm.specAddr = new String(); } reqForm.specPhone = request.getParameter("phone"); if (reqForm.specPhone == null){ reqForm.specPhone = ""; } reqForm.specFax = request.getParameter("fax"); if (reqForm.specFax == null){ reqForm.specFax = ""; } //Create new file to save form to String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); String fileName = path + "ConsultationRequestForm-"+UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")+".pdf"; FileOutputStream out = new FileOutputStream(fileName); //Create the document we are going to write to document = new Document(); // writer = PdfWriter.getInstance(document,out); writer = PdfWriterFactory.newInstance(document, out, FontSettings.HELVETICA_6PT); //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props' reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf"); Rectangle pSize = reader.getPageSize(1); height = pSize.getHeight(); document.setPageSize(pSize); document.addTitle("Consultation Form Request"); document.addCreator("OSCAR"); document.open(); //Create the font we are going to print to bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = writer.getDirectContent(); ct = new ColumnText(cb); cb.setColorStroke(new Color(0,0,0)); // start writing the pdf document PdfImportedPage page1 = writer.getImportedPage(reader, 1); cb.addTemplate(page1, 1, 0, 0, 1, 0, 0); // addFooter(); setAppointmentInfo(reqForm); // add the dynamically positioned text elements float dynamicHeight = 0; dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm); document.close(); reader.close(); writer.close(); out.close(); // combine the recently created pdf with any pdfs that were added to the consultation request form combinePDFs(loggedInInfo, fileName); }
@Override public void draw() { TabSegment segment = segments.get(segmentIndex); float advance = segment.layout.getAdvance(); ColumnText colText = new ColumnText(pdfContentByte); colText.setSimpleColumn( pdfExporter.getPhrase(segment.as, segment.text, text), x + drawPosX + leftOffsetFactor * advance,// + leftPadding pdfExporter.getCurrentPageFormat().getPageHeight() - y - topPadding - verticalAlignOffset //- text.getLeadingOffset() + lineHeight - drawPosY, x + drawPosX + segment.layout.getAdvance() + rightOffsetFactor * advance,// + leftPadding pdfExporter.getCurrentPageFormat().getPageHeight() - y - topPadding - verticalAlignOffset //- text.getLeadingOffset() -400//+ lineHeight//FIXMETAB - drawPosY, 0,//text.getLineSpacingFactor(),// * text.getFont().getSize(), horizontalAlignment ); //colText.setLeading(0, text.getLineSpacingFactor());// * text.getFont().getSize()); colText.setLeading(lineHeight); colText.setRunDirection( text.getRunDirectionValue() == RunDirectionEnum.LTR ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_RTL ); try { colText.go(); } catch (DocumentException e) { throw new JRRuntimeException(e); } }
public void addTitlePage(String evaltitle, String groupNames, String startDate, String endDate, String responseInformation, byte[] bannerImageBytes, String evalSystemTitle, String informationTitle) { try { float pagefooter = paragraphFont.getSize(); PdfContentByte cb = pdfWriter.getDirectContent(); float docMiddle = (document.right() - document.left()) / 2 + document.leftMargin(); Paragraph emptyPara = new Paragraph(" "); emptyPara.setSpacingAfter(100.0f); // Title Paragraph titlePara = new Paragraph("\n\n\n" + evaltitle, frontTitleFont); titlePara.setAlignment(Element.ALIGN_CENTER); document.add(titlePara); // Groups Paragraph groupPara = new Paragraph(groupNames, frontAuthorFont); groupPara.setSpacingBefore(25.0f); groupPara.setAlignment(Element.ALIGN_CENTER); document.add(groupPara); // Little info area? I don't know, it was on the mockup though Paragraph infoPara = new Paragraph(informationTitle, frontInfoFont); infoPara.setAlignment(Element.ALIGN_CENTER); infoPara.setSpacingBefore(90.0f); document.add(infoPara); // Started on Paragraph startedPara = new Paragraph(startDate, frontInfoFont); startedPara.setAlignment(Element.ALIGN_CENTER); startedPara.setSpacingBefore(25.0f); document.add(startedPara); // Ended on Paragraph endedPara = new Paragraph(endDate, frontInfoFont); endedPara.setAlignment(Element.ALIGN_CENTER); endedPara.setSpacingBefore(25.0f); document.add(endedPara); // Reply Rate Paragraph replyRatePara = new Paragraph(responseInformation, frontInfoFont); replyRatePara.setAlignment(Element.ALIGN_CENTER); replyRatePara.setSpacingBefore(25.0f); document.add(replyRatePara); // Logo and Tagline cb.beginText(); cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 12); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, evalSystemTitle, docMiddle, document .bottom() + 20, 0); cb.endText(); if (bannerImageBytes != null) { Image banner = Image.getInstance(bannerImageBytes); cb.addImage(banner, banner.getWidth(), 0, 0, banner.getHeight(), docMiddle - (banner.getWidth() / 2), document.bottom() + 35); } document.newPage(); responseArea = new ColumnText(cb); responseArea.setSimpleColumn(document.left(),document.top(),document.right()/2, document.bottom()+pagefooter); responseArea.go(); } catch (DocumentException | IOException de) { throw UniversalRuntimeException.accumulate(de, "Unable to create title page"); } }
/** * Layer radio group and zoom. * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("layer radio group and zoom"); try { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "layers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer radio group and zoom", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer title = PdfLayer.createTitle("Layer radio group", writer); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayer l4 = new PdfLayer("Layer 4", writer); title.addChild(l1); title.addChild(l2); title.addChild(l3); l4.setZoom(2, -1); l4.setOnPanel(false); l4.setPrint("Print", true); l2.setOn(false); l3.setOn(false); ArrayList radio = new ArrayList(); radio.add(l1); radio.add(l2); radio.add(l3); writer.addOCGRadioGroup(radio); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2"); Phrase p3 = new Phrase("Text in layer 3"); Phrase p4 = new Phrase("Text in layer 4"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(l2); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.beginLayer(l4); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p4, 50, 450, 0); cb.endLayer(); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("<< Zoom here!", new Font(Font.COURIER, 12, Font.NORMAL, Color.blue)), 150, 450, 0); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
/** * Automatic grouping and nesting. * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Automatic grouping and nesting"); try { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "automatic.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Automatic layer grouping and nesting", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l12 = new PdfLayer("Layer nesting", writer); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer title = PdfLayer.createTitle("Layer grouping", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayer l4 = new PdfLayer("Layer 4", writer); l12.addChild(l1); l12.addChild(l2); title.addChild(l3); title.addChild(l4); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2"); Phrase p3 = new Phrase("Text in layer 3"); Phrase p4 = new Phrase("Text in layer 4"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(l2); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.beginLayer(l4); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p4, 50, 450, 0); cb.endLayer(); cb.sanityCheck(); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
/** * Adding text at absolute positions. * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Text at absolute positions"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "complextext.pdf")); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); // first we draw some lines to be able to visualize the text // alignment functions cb.setLineWidth(0f); cb.moveTo(250, 500); cb.lineTo(250, 800); cb.moveTo(50, 700); cb.lineTo(400, 700); cb.moveTo(50, 650); cb.lineTo(400, 650); cb.moveTo(50, 600); cb.lineTo(400, 600); cb.stroke(); // we construct a font //Don't use path read ttf into byte[] instead // BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arialuni.ttf", BaseFont.IDENTITY_H, true); InputStream inputStream = PdfTestRunner.getActivity().getResources().openRawResource(R.raw.freesans); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); BaseFont bf = BaseFont.createFont("freesans.ttf", BaseFont.IDENTITY_H, true, false, buffer, null); Font ft = new Font(bf, 12); // This is the text: String text = "\u0623\u0648\u0631\u0648\u0628\u0627, \u0628\u0631\u0645\u062c\u064a\u0627\u062a \u0627\u0644\u062d\u0627\u0633\u0648\u0628 + \u0627\u0646\u062a\u0631\u0646\u064a\u062a :"; Phrase center = new Phrase(text + " Center", ft); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_CENTER, center, 250, 700, 0, PdfWriter.RUN_DIRECTION_RTL, 0); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_RIGHT, new Phrase(text + " Right", ft), 250, 650, 20, PdfWriter.RUN_DIRECTION_RTL, 0); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, new Phrase("Some text Left aligned", ft), 250, 600, 20); float size = ColumnText.getWidth(center, PdfWriter.RUN_DIRECTION_RTL, 0); cb.setRGBColorStroke(255, 0, 0); cb.rectangle(250 - size / 2, 690, size, 30); cb.stroke(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
/** * Demonstrates some Layer functionality. * * @param args * no arguments needed here */ public static void main(String[] args) { System.out.println("layers"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "Layers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseOC); document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer grouping", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); PdfArray group = new PdfArray(); group.add(new PdfString("A group of two", PdfObject.TEXT_UNICODE)); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
/** * Demonstrating the use of ColumnText * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Simple Column"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "columnsimple.pdf")); // step 3: we open the document document.open(); // step 4: // we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font font = new Font(bf, 11, Font.NORMAL); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(60, 300, 100, 300 + 28 * 15, 15, Element.ALIGN_CENTER); ct.addText(new Phrase(15, "UNI\n", font)); for (int i = 0; i < 27; i++) { ct.addText(new Phrase(15, uni[i] + "\n", font)); } ct.go(); cb.rectangle(103, 295, 52, 8 + 28 * 15); cb.stroke(); ct.setSimpleColumn(105, 300, 150, 300 + 28 * 15, 15, Element.ALIGN_RIGHT); ct.addText(new Phrase(15, "char\n", font)); for (int i = 0; i < 27; i++) { ct.addText(new Phrase(15, code[i] + "\n", font)); } ct.go(); ct.setSimpleColumn(160, 300, 500, 300 + 28 * 15, 15, Element.ALIGN_LEFT); ct.addText(new Phrase(15, "NAME" + "\n", font)); for (int i = 0; i < 27; i++) { ct.addText(new Phrase(15, name[i] + "\n", font)); } ct.go(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
/** * Demonstrating the use of ColumnText * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Simple single object columns"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "column.pdf")); // step 3: we open the document document.open(); // step 4: // we create some content BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font font = new Font(bf, 11, Font.NORMAL); Phrase unicodes = new Phrase(15, "UNI\n", font); Phrase characters = new Phrase(15, "\n", font); Phrase names = new Phrase(15, "NAME\n", font); for (int i = 0; i < 27; i++) { unicodes.add(uni[i] + "\n"); characters.add(code[i] + "\n"); names.add(name[i] + "\n"); } // we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(unicodes, 60, 300, 100, 300 + 28 * 15, 15, Element.ALIGN_CENTER); ct.go(); cb.rectangle(103, 295, 52, 8 + 28 * 15); cb.stroke(); ct.setSimpleColumn(characters, 105, 300, 150, 300 + 28 * 15, 15, Element.ALIGN_RIGHT); ct.go(); ct.setSimpleColumn(names, 160, 300, 500, 300 + 28 * 15, 15, Element.ALIGN_LEFT); ct.go(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
public void printPdf() throws IOException, DocumentException{ EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil(); reqForm.estRequestFromId((String) request.getAttribute("reqId")); //make sure we have data to print if( reqForm == null ) throw new DocumentException(); // init req form info reqForm.specAddr = request.getParameter("address"); if (reqForm.specAddr == null){reqForm.specAddr = new String(); } reqForm.specPhone = request.getParameter("phone"); if (reqForm.specPhone == null){ reqForm.specPhone = ""; } reqForm.specFax = request.getParameter("fax"); if (reqForm.specFax == null){ reqForm.specFax = ""; } //Create new file to save form to String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); String fileName = path + "ConsultationRequestForm-"+UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")+".pdf"; FileOutputStream out = new FileOutputStream(fileName); //Create the document we are going to write to document = new Document(); writer = PdfWriter.getInstance(document,out); //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props' reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf"); Rectangle pSize = reader.getPageSize(1); width = pSize.getWidth(); height = pSize.getHeight(); document.setPageSize(pSize); document.addTitle("Consultation Form Request"); document.addCreator("OSCAR"); document.open(); //Create the font we are going to print to bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = writer.getDirectContent(); ct = new ColumnText(cb); cb.setColorStroke(new Color(0,0,0)); // start writing the pdf document PdfImportedPage page1 = writer.getImportedPage(reader, 1); cb.addTemplate(page1, 1, 0, 0, 1, 0, 0); addFooter(); setAppointmentInfo(reqForm); // add the dynamically positioned text elements float dynamicHeight = 0; dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight, reqForm); dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm); document.close(); reader.close(); writer.close(); out.close(); // combine the recently created pdf with any pdfs that were added to the consultation request form combinePDFs(fileName); }
/** * 添加水印、页眉、页脚 * @param fileName 源文件路径 * @param savepath 目标文件路径 * @param waterMarkName 文字水印 * @param pageHeade 页眉 * @param foot 页脚 * @return */ public static int addFooterAndWater(String fileName, String savepath, String waterMarkName, String pageHeade, String foot) { // 文档总页数 int num = 0; Document document = new Document(); try { PdfReader reader = new PdfReader(fileName); //BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); BaseFont base = BaseFont.createFont(BaseFont.COURIER, "utf-8", BaseFont.EMBEDDED); num = reader.getNumberOfPages(); PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath)); document.open(); for (int i = 0; i < num;) { PdfImportedPage page = copy.getImportedPage(reader, ++i); PageStamp stamp = copy.createPageStamp(page); Font f = new Font(base); // 添加页脚,左侧文字,右侧页码 ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_RIGHT, new Phrase(String.format("第 %d 页/共 %d 页", i, num), f), 550f, 28, 0); ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_LEFT, new Phrase(foot, f), 50f, 28, 0); // 添加页眉 (文字页眉,居中) ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_CENTER, new Phrase(pageHeade, f), 150f, 800, 0); // 页眉添加logo (图片页眉,居右) Image img = Image.getInstance("F:\\Tools\\pdf2swf工具\\resource/watermark.png");//"template/logo.png");// 选择图片 img.setAlignment(1); img.scaleAbsolute(436 / 5, 96 / 5);// 控制图片大小 img.setAbsolutePosition(450f, 800);// 控制图片位置 stamp.getUnderContent().addImage(img); // 添加水印 PdfContentByte under = stamp.getUnderContent(); under.beginText(); under.setColorFill(Color.LIGHT_GRAY); // 字符越长,字体越小,设置字体 int fontSize = getFontSize(waterMarkName); under.setFontAndSize(base, fontSize); // 设置水印文字字体倾斜 开始 float pageWidth = reader.getPageSize(i).getWidth(); float pageHeight = reader.getPageSize(i).getHeight(); // 水印文字成60度角倾斜,且页面居中展示 //under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, pageWidth / 2, pageHeight / 2, 60); img.setAlignment(1); img.scaleAbsolute(636 / 5, 126 / 5);// 控制图片大小 img.setAbsolutePosition(pageWidth / 2, pageHeight / 2);// 控制图片位置 img.setRotation(60); stamp.getUnderContent().addImage(img); // 字体设置结束 under.endText(); stamp.alterContents(); copy.addPage(page); } } catch (Exception e) { e.printStackTrace(); return -1; } finally { if (null != document) { document.close(); } } System.out.println("pdf totalpages:" + num); return num; }
/** * Demonstrates the use of nested layers * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("nested layers"); try { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "nestedlayers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer nesting", new Font(Font.HELVETICA, 20, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l23 = new PdfLayer("Top Layer 2 3", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0); cb.endLayer(); cb.beginLayer(l23); cb.beginLayer(l2); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); cb.endLayer(); cb.sanityCheck(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); order.add(l23.getRef()); PdfArray group = new PdfArray(); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
/** * 添加水印 * @author weird * @version 1.0 * @param writer * @param document */ private void addWatermark(PdfWriter writer, Document document) { String content = "generate by apiresolver"; ColumnText.showTextAligned(writer.getDirectContentUnder(), Element.ALIGN_CENTER, ItextUtil.getFontSelector(35, Font.NORMAL, new Color(240, 240, 240)).process(content), 250, 400, 25); }