List of usage examples for com.itextpdf.text Rectangle getTop
public float getTop()
From source file:com.vectorprint.report.itext.style.stylers.AbstractFieldStyler.java
License:Open Source License
@Override protected void draw(PdfContentByte canvas, float x, float y, float width, float height, String genericTag) throws VectorPrintException { Rectangle box = new Rectangle(x, y, x + width, y - height); PdfFormField pff = null;/*from w w w . j a v a2 s. co m*/ if (getValue(DocumentSettings.WIDTH, Float.class) > 0) { box.setRight(box.getLeft() + getValue(DocumentSettings.WIDTH, Float.class)); } if (getValue(DocumentSettings.HEIGHT, Float.class) > 0) { float diff = box.getHeight() - getValue(DocumentSettings.HEIGHT, Float.class); box.setBottom(box.getBottom() + diff / 2); box.setTop(box.getTop() - diff / 2); } bf.setBox(box); try { List<BaseStyler> stylers = stylerFactory.getStylers(getStyleClass()); List<FormFieldStyler> ffStylers = StyleHelper.getStylers(stylers, FormFieldStyler.class); pff = makeField(); if (FormFieldStyler.FIELDTYPE.BUTTON.equals(getFieldtype())) { for (FormFieldStyler f : ffStylers) { if (f.isParameterSet(Image.URLPARAM)) { pff.setAction(PdfAction.createSubmitForm(f.getValue(Image.URLPARAM, URL.class).toString(), null, PdfAction.SUBMIT_HTML_FORMAT)); break; } } } } catch (IOException | DocumentException | VectorPrintException ex) { throw new VectorPrintRuntimeException(ex); } getWriter().addAnnotation(pff); if (stylerFactory.getSettings().getBooleanProperty(false, DEBUG)) { DebugHelper.debugRect(canvas, box, new float[] { 2, 2 }, 0.7f, stylerFactory.getSettings(), elementProducer); DebugHelper.styleLink(canvas, getStyleClass(), "", box.getLeft(), box.getTop(), stylerFactory.getSettings(), elementProducer); } }
From source file:com.vectorprint.report.itext.style.stylers.AbstractPositioning.java
License:Open Source License
/** * Calls {@link #draw(com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, String) } with rect.getLeft() * + getShiftx(), rect.getTop() + getShifty(), rect.getWidth(), rect.getHeight(), genericTag. When {@link #isShadow() * } is true {@link #isDrawShadow() } will be set to true, prior to calling * {@link #draw(com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, java.lang.String) } and to false * afterwards.//w w w . j a v a 2 s. com * * @param rect * @param genericTag passed on to abstract method * @throws VectorPrintException * @see EventHelper#onGenericTag(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, * com.itextpdf.text.Rectangle, java.lang.String) */ @Override public final void draw(Rectangle rect, String genericTag) throws VectorPrintException { if (getValue(SHADOW, Boolean.class)) { drawShadow(rect.getLeft() + getShiftx(), rect.getTop() + getShifty(), rect.getWidth(), rect.getHeight(), genericTag); } PdfContentByte canvas = getPreparedCanvas(); draw(canvas, rect.getLeft() + getShiftx(), rect.getTop() + getShifty(), rect.getWidth(), rect.getHeight(), genericTag); resetCanvas(canvas); }
From source file:com.vectorprint.report.itext.style.stylers.AdvancedImpl.java
License:Open Source License
/** * An advanced styler may be added as event to a cell by {@link StyleHelper#style(java.lang.Object, java.lang.Object, java.util.Collection) } * when the element styled is a table and the {@link EVENTMODE} is ALL or CELL. This enables drawing near a cell. * Calls {@link #draw(com.itextpdf.text.Rectangle, java.lang.String) } with the rectangle of the cell and null as genericTag. When * {@link #USEPADDING} is true the rectangle is calculated taking cell padding into account. * * @see EVENTMODE#CELL/*from w w w . j av a 2 s . c o m*/ * @param cell * @param position * @param canvases */ @Override public final void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { try { tableForeground = isBg() ? canvases[PdfPTable.BASECANVAS] : canvases[PdfPTable.TEXTCANVAS]; Rectangle box = getValue(USEPADDING, Boolean.class) ? new Rectangle(position.getLeft() + cell.getPaddingLeft(), position.getBottom() + cell.getPaddingBottom(), position.getRight() - cell.getPaddingRight(), position.getTop() - cell.getPaddingTop()) : position; draw(box, null); tableForeground = null; } catch (VectorPrintException ex) { throw new VectorPrintRuntimeException(ex); } }
From source file:controller.CCInstance.java
License:Open Source License
public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings, final SignatureListener sl) throws CertificateException, IOException, DocumentException, KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { PrivateKey pk;// ww w. ja va 2 s . c o m final PdfReader reader = new PdfReader(pdfPath); pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias()); if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { String message = Bundle.getBundle().getString("fileDoesNotAllowChanges"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) { settings.setPageNumber(reader.getNumberOfPages() - 1); } if (null == pk) { String message = Bundle.getBundle().getString("noSmartcardFound"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) { String message = Bundle.getBundle().getString("certificateNullChain"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain(); final Certificate owner = embeddedCertificateChain.get(0); final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1); if (null == owner) { String message = Bundle.getBundle().getString("certificateNameUnknown"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final X509Certificate X509C = ((X509Certificate) lastCert); final Calendar now = Calendar.getInstance(); final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain( X509C); final Certificate[] fullCertificateChain; if (filledMissingCertsFromChainInTrustedKeystore.length < 2) { fullCertificateChain = new Certificate[embeddedCertificateChain.size()]; for (int i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } } else { fullCertificateChain = new Certificate[embeddedCertificateChain.size() + filledMissingCertsFromChainInTrustedKeystore.length - 1]; int i = 0; for (i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) { fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f]; } } // Leitor e Stamper FileOutputStream os = null; try { os = new FileOutputStream(destination); } catch (FileNotFoundException e) { String message = Bundle.getBundle().getString("outputFileError"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new IOException(message); } // Aparncia da Assinatura final char pdfVersion; switch (Settings.getSettings().getPdfVersion()) { case "/1.2": pdfVersion = PdfWriter.VERSION_1_2; break; case "/1.3": pdfVersion = PdfWriter.VERSION_1_3; break; case "/1.4": pdfVersion = PdfWriter.VERSION_1_4; break; case "/1.5": pdfVersion = PdfWriter.VERSION_1_5; break; case "/1.6": pdfVersion = PdfWriter.VERSION_1_6; break; case "/1.7": pdfVersion = PdfWriter.VERSION_1_7; break; default: pdfVersion = PdfWriter.VERSION_1_7; } final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0 ? PdfStamper.createSignature(reader, os, pdfVersion) : PdfStamper.createSignature(reader, os, pdfVersion, null, true)); final PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setSignDate(now); appearance.setReason(settings.getReason()); appearance.setLocation(settings.getLocation()); appearance.setCertificationLevel(settings.getCertificationLevel()); appearance.setSignatureCreator(SIGNATURE_CREATOR); appearance.setCertificate(owner); final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath)); if (settings.isVisibleSignature()) { appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1, fieldName); appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION); if (null != settings.getAppearance().getImageLocation()) { appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation())); } com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0) .getBaseFont()); font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB())); if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) { font.setStyle(Font.BOLD + Font.ITALIC); } else if (settings.getAppearance().isBold()) { font.setStyle(Font.BOLD); } else if (settings.getAppearance().isItalic()) { font.setStyle(Font.ITALIC); } else { font.setStyle(Font.PLAIN); } appearance.setLayer2Font(font); String text = ""; if (settings.getAppearance().isShowName()) { if (!settings.getCcAlias().getName().isEmpty()) { text += settings.getCcAlias().getName() + "\n"; } } if (settings.getAppearance().isShowReason()) { if (!settings.getReason().isEmpty()) { text += settings.getReason() + "\n"; } } if (settings.getAppearance().isShowLocation()) { if (!settings.getLocation().isEmpty()) { text += settings.getLocation() + "\n"; } } if (settings.getAppearance().isShowDate()) { DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("Z"); text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n"; } if (!settings.getText().isEmpty()) { text += settings.getText(); } PdfTemplate layer2 = appearance.getLayer(2); Rectangle rect = settings.getPositionOnDocument(); Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight()); float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT); ColumnText ct = new ColumnText(layer2); ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT); ct.setAlignment(Element.ALIGN_MIDDLE); int align; switch (settings.getAppearance().getAlign()) { case 0: align = Element.ALIGN_LEFT; break; case 1: align = Element.ALIGN_CENTER; break; case 2: align = Element.ALIGN_RIGHT; break; default: align = Element.ALIGN_LEFT; } ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(), size, align); ct.go(); } else { appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName); } // CRL <- Pesado! final ArrayList<CrlClient> crlList = null; // OCSP OcspClient ocspClient = new OcspClientBouncyCastle(); // TimeStamp TSAClient tsaClient = null; if (settings.isTimestamp()) { tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null); } final String hashAlg = getHashAlgorithm(X509C.getSigAlgName()); final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName()); final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName()); try { MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient, 0, MakeSignature.CryptoStandard.CMS); if (sl != null) { sl.onSignatureComplete(pdfPath, true, ""); } return true; } catch (Exception e) { os.flush(); os.close(); new File(destination).delete(); if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled")); } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions")); } else if (e instanceof ExceptionConverter) { String message = Bundle.getBundle().getString("timestampFailed"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } else { if (sl != null) { sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog")); } controller.Logger.getLogger().addEntry(e); } return false; } }
From source file:dbedit.actions.ExportPdfAction.java
License:Open Source License
@Override protected void performThreaded(ActionEvent e) throws Exception { boolean selection = false; JTable table = ResultSetTable.getInstance(); if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) { Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE, new Object[] { "Everything", "Selection" }, "Everything"); if (option == null || "-1".equals(option.toString())) { return; }/*from ww w.j a v a2 s. c om*/ selection = "Selection".equals(option); } List list = ((DefaultTableModel) table.getModel()).getDataVector(); int columnCount = table.getColumnCount(); PdfPTable pdfPTable = new PdfPTable(columnCount); pdfPTable.setWidthPercentage(100); pdfPTable.getDefaultCell().setPaddingBottom(4); int[] widths = new int[columnCount]; // Row Header pdfPTable.getDefaultCell().setBorderWidth(2); for (int i = 0; i < columnCount; i++) { String columnName = table.getColumnName(i); pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT)); widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " "))); } pdfPTable.getDefaultCell().setBorderWidth(1); if (!list.isEmpty()) { pdfPTable.setHeaderRows(1); } // Body for (int i = 0; i < list.size(); i++) { if (!selection || table.isRowSelected(i)) { List record = (List) list.get(i); for (int j = 0; j < record.size(); j++) { Object o = record.get(j); if (o != null) { if (ResultSetTable.isLob(j)) { o = Context.getInstance().getColumnTypeNames()[j]; } } else { o = ""; } PdfPCell cell = new PdfPCell(new Phrase(o.toString())); cell.setPaddingBottom(4); if (o instanceof Number) { cell.setHorizontalAlignment(Element.ALIGN_RIGHT); } pdfPTable.addCell(cell); widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString()))); } } } // Size pdfPTable.setWidths(widths); int totalWidth = 0; for (int width : widths) { totalWidth += width; } Rectangle pageSize = PageSize.A4.rotate(); pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f)); pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f)); // Document Document document = new Document(pageSize); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream); document.open(); pdfTemplate = writer.getDirectContent().createTemplate(100, 100); pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100)); writer.setPageEvent(this); document.add(pdfPTable); document.close(); FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray()); }
From source file:de.gbv.marginalia.Marginalia.java
License:Open Source License
/** * Inspect a PDF file and write the info to a writer * @param writer Writer to a text file/* ww w .ja v a 2s.c o m*/ * @param filename Path to the PDF file * @throws IOException */ public static void inspect(PrintWriter writer, String filename) throws IOException, SAXException { // writer.println(filename); writer.flush(); PdfReader reader = new PdfReader(filename); ContentHandler xmlhandler = new SimpleXMLWriter(writer); xmlhandler.startDocument(); SimpleXMLCreator xml = new SimpleXMLCreator(xmlhandler, Annotation.namespaces, true); /* writer.println("Number of pages: "+reader.getNumberOfPages()); Rectangle mediabox = reader.getPageSize(1); writer.print("Size of page 1: ["); writer.print(mediabox.getLeft()); writer.print(','); writer.print(mediabox.getBottom()); writer.print(','); writer.print(mediabox.getRight()); writer.print(','); writer.print(mediabox.getTop()); writer.println("]"); writer.print("Rotation of page 1: "); writer.println(reader.getPageRotation(1)); writer.print("Page size with rotation of page 1: "); writer.println(reader.getPageSizeWithRotation(1)); writer.println(); writer.flush(); */ List<Annotation> annots = new LinkedList<Annotation>(); xml.startElement("annots"); // TODO: The following elements may be added: // - optionally write <f href="Document.pdf"/> // - optionally write <ids original="ID" modified="ID" /> xml.startElement("m", "pages"); for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) { PdfDictionary pageDic = reader.getPageN(pageNum); Map<String, String> attr = new HashMap<String, String>(); attr.put("number", "" + pageNum); attr.put("rotate", "" + reader.getPageRotation(pageNum)); Rectangle mediabox = reader.getPageSize(pageNum); attr.put("left", "" + mediabox.getLeft()); attr.put("bottom", "" + mediabox.getBottom()); attr.put("right", "" + mediabox.getRight()); attr.put("top", "" + mediabox.getTop()); xml.contentElement("m", "page", "", attr); PdfArray rawannots = pageDic.getAsArray(PdfName.ANNOTS); if (rawannots == null || rawannots.isEmpty()) { // writer.println("page "+pageNum+" contains no annotations"); continue; } // writer.println("page "+pageNum+" has "+rawannots.size()+" annotations"); for (int i = 0; i < rawannots.size(); i++) { PdfObject obj = rawannots.getDirectObject(i); if (!obj.isDictionary()) continue; Annotation a = new Annotation((PdfDictionary) obj, pageNum); annots.add(a); } /** // Now we have all highlight and similar annotations, we need // to find out what words are actually highlighted! PDF in fact // is a dump format to express documents. // For some hints see // http://stackoverflow.com/questions/4028240/extract-each-column-of-a-pdf-file // We could reuse code from LocationTextExtractionStrategy (TODO) // LocationTextExtractionStrategy extr = new LocationTextExtractionStrategy(); String fulltext = PdfTextExtractor.getTextFromPage(reader,pageNum);//,extr writer.println(fulltext); */ } xml.endElement(); for (Annotation a : annots) { a.serializeXML(xmlhandler); } // TODO: add page information (page size and orientation) xml.endAll(); }
From source file:EplanPrinter.PDFPrint.java
License:Open Source License
private MediaBox[] getDocumentMediaBox(PdfReader reader, int pages) { MediaBox mbox[] = new MediaBox[pages]; Rectangle rect; for (int x = 0; x < totalPages; x++) { mbox[x] = new MediaBox(); rect = reader.getPageSize(x + 1); mbox[x].top = rect.getTop(); mbox[x].bottom = rect.getBottom(); mbox[x].left = rect.getLeft();/* w ww . jav a2 s . c om*/ mbox[x].right = rect.getRight(); } return mbox; }
From source file:fenix.planner.pdf.PDFGenerator.java
License:Open Source License
public void generate(OutputStream output) { final Rectangle pageSize = PageSize.A4; final ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream(); document = new Document(pageSize, LEFT_MARGIN, RIGHT_MARGIN, TOP_MARGIN, BOTTOM_MARGIN); try {// ww w . ja va 2s .co m final PdfWriter writer = PdfWriter.getInstance(document, outputBuffer); writer.setBoxSize("art", new Rectangle(ART_BOX_LEFT_MARGIN, ART_BOX_BOTTOM_MARGIN, pageSize.getRight() - ART_BOX_RIGHT_MARGIN, pageSize.getTop() - ART_BOX_TOP_MARGIN)); writer.setPageEvent(new HeaderFooter()); document.open(); createAndAddForeword(); createAndAddEventTable(); createAndAddAfterword(); createAndAddOrganizerTable(); document.close(); writer.close(); // Loop through the document again to add the missing page numbers document = new Document(); final PdfCopy copy = new PdfCopy(document, output); document.open(); final PdfReader reader = new PdfReader(outputBuffer.toByteArray()); addPageNumbers(reader, copy); document.close(); reader.close(); } catch (DocumentException | IOException ex) { throw new PDFGenerationException("Error generating PDF", ex); } }
From source file:helpers.PDFHeaderFooter.java
@Override public void onStartPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(""), rect.getLeft(), rect.getTop(), 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Page " + document.getPageNumber(), FontFactory.getFont(FontFactory.TIMES_ITALIC, 5, Font.ITALIC, BaseColor.BLACK)), rect.getRight(), rect.getTop(), 0); }
From source file:hsa.awp.admingui.report.util.HeaderFooter.java
License:Open Source License
/** * this method is called by Pageevent.// w w w . j av a 2 s .co m * * @param writer write of the document * @param document document it self */ public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); /* title */ ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(title, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16)), rect.getLeft(), rect.getTop() + 20, 0); /* subtitle */ ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(subtitle, FontFactory.getFont(FontFactory.HELVETICA, 9)), rect.getLeft(), rect.getTop() + 9, 0); /* date */ DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); java.util.Date date = new java.util.Date(); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(dateFormat.format(date)), rect.getRight(), rect.getTop() + 15, 0); /* pagenumber */ ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(String.format("Seite %d", writer.getPageNumber())), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 25, 0); }