public void onEndPage(PdfWriter pdfWriter, Document document) { pageNum++; // 页面计数 if (needNotFootAndHead && pageNum >= needNotFootAndHeadPageNum) { return; } PdfContentByte pdfContByte = pdfWriter.getDirectContent(); pdfContByte.saveState(); pdfContByte.setGState(pdfGState); pdfContByte.setFontAndSize(baseFont, 48); pdfContByte.endText(); Image barCodeImge = code39.createImageWithBarcode(pdfContByte, null, null); try { pdfContByte.addImage( headerImage, headerImage.getWidth() / 2, 0, 0, headerImage.getHeight() / 2, document.left() + 65, document.top() + 10); pdfContByte.addImage( barCodeImge, barCodeImge.getWidth(), 0, 0, barCodeImge.getHeight(), document.left() + 35, document.bottom() - 26); } catch (Exception ex) { throw new ExceptionConverter(ex); } pdfContByte.restoreState(); pdfContByte.saveState(); String headFootText = "保险合同号:" + this.contNo; float headTextPos = document.top() + 10; pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 10); pdfContByte.setTextMatrix(document.right() - 175, headTextPos); pdfContByte.showText(headFootText); pdfContByte.endText(); pdfContByte.saveState(); // cell.setBorder(Rectangle.BOTTOM); // String metLife = "中美大都会人寿保险有限公司"; // float footTextPos = document.bottom()-12; // pdfContByte.beginText(); // pdfContByte.setFontAndSize(baseFont, 7); // pdfContByte.setTextMatrix(document.left()+50, footTextPos); // pdfContByte.showText(metLife); // pdfContByte.endText(); // pdfContByte.saveState(); String shanghaimetLife = "中美联泰大都会人寿保险有限公司"; float shanghaifootText = document.bottom(); pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 7); pdfContByte.setTextMatrix(document.left() + 35, shanghaifootText); pdfContByte.showText(shanghaimetLife); pdfContByte.endText(); pdfContByte.saveState(); String shanghaimetLifeAddress = " 联系地址:上海市黄浦区黄陂北路227号中区广场11楼"; float shanghaifootTextAddPos = document.bottom(); pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 7); pdfContByte.setTextMatrix(document.right() - 190, shanghaifootTextAddPos); pdfContByte.showText(shanghaimetLifeAddress); pdfContByte.endText(); pdfContByte.saveState(); String metLifeAddress = "北京东城区东长安街一号东方广场东方经贸城东二办公楼12层"; float footTextAddPos = document.bottom() - 8; pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 7); pdfContByte.setTextMatrix(document.right() - 190, footTextAddPos); pdfContByte.showText(metLifeAddress); pdfContByte.endText(); pdfContByte.saveState(); String metLifeCustSer = "客户服务热线:400 818 8168"; float footTextCSPos = document.bottom() - 16; pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 7); pdfContByte.setTextMatrix(document.right() - 85, footTextCSPos); pdfContByte.showText(metLifeCustSer); pdfContByte.endText(); pdfContByte.saveState(); String metLifeSite = "http://www.metlife.com.cn/"; float footTextSTPos = document.bottom() - 24; pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 7); pdfContByte.setTextMatrix(document.right() - 75, footTextSTPos); pdfContByte.showText(metLifeSite); pdfContByte.endText(); pdfContByte.saveState(); // String pageNumText = "第 " + pdfWriter.getPageNumber() + " 页"; String pageNumText = String.valueOf(pdfWriter.getPageNumber()); float textBase = document.bottom() - 2; pdfContByte.beginText(); pdfContByte.setFontAndSize(baseFont, 9); pdfContByte.setTextMatrix(document.left() + 285, textBase); pdfContByte.showText(pageNumText); pdfContByte.endText(); pdfContByte.saveState(); }
private void doActionAddWatermark() throws PageException, IOException, DocumentException { required("pdf", "addWatermark", "source", source); if (copyFrom == null && image == null) throw new ApplicationException( "at least one of the following attributes must be defined " + "[copyFrom,image]"); if (destination != null && destination.exists() && !overwrite) throw new ApplicationException("destination file [" + destination + "] already exists"); // image Image img = null; if (image != null) { railo.runtime.img.Image ri = railo.runtime.img.Image.createImage(pageContext, image, false, false, true); img = Image.getInstance(ri.getBufferedImage(), null, false); } // copy From else { byte[] barr; try { Resource res = Caster.toResource(pageContext, copyFrom, true); barr = IOUtil.toBytes(res); } catch (ExpressionException ee) { barr = Caster.toBinary(copyFrom); } img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false); } // position float x = UNDEFINED, y = UNDEFINED; if (!StringUtil.isEmpty(position)) { int index = position.indexOf(','); if (index == -1) throw new ApplicationException( "attribute [position] has a invalid value [" + position + "]," + "value should follow one of the following pattern [40,50], [40,] or [,50]"); String strX = position.substring(0, index).trim(); String strY = position.substring(index + 1).trim(); if (!StringUtil.isEmpty(strX)) x = Caster.toIntValue(strX); if (!StringUtil.isEmpty(strY)) y = Caster.toIntValue(strY); } PDFDocument doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); reader.consolidateNamedDestinations(); boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output OutputStream os = null; if (!StringUtil.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } try { int len = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); if (len > 0) { if (x == UNDEFINED || y == UNDEFINED) { PdfImportedPage first = stamp.getImportedPage(reader, 1); if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2; if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2; } img.setAbsolutePosition(x, y); // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte } // rotation if (rotation != 0) { img.setRotationDegrees(rotation); } Set _pages = doc.getPages(); for (int i = 1; i <= len; i++) { if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue; PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i); PdfGState gs1 = new PdfGState(); // print.out("op:"+opacity); gs1.setFillOpacity(opacity); // gs1.setStrokeOpacity(opacity); cb.setGState(gs1); cb.addImage(img); } if (bookmarks != null) stamp.setOutlines(master); stamp.close(); } finally { IOUtil.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) IOUtil.copy( new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true); // MUST overwrite if (!StringUtil.isEmpty(name)) { pageContext.setVariable( name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password)); } } } }
private void drawOGHeader( Document document, UserShopForm sForm, String pImageName, boolean personal) throws DocumentException { // add the logo try { Image i = Image.getInstance(pImageName); float x = document.leftMargin(); float y = document.getPageSize().getHeight() - i.getHeight() - 5; i.setAbsolutePosition(x, y); document.add(i); } catch (Exception e) { e.printStackTrace(); } if (catalogOnly) { return; } // unfortuanately this means we are limited to PDF rendering only. // get the user's personal info PdfPTable personalInfo; if (personal) { personalInfo = getPersonalized(sForm); } else { personalInfo = getNonPersonalized(sForm); } if (null != sForm.getAppUser().getUserAccount() && null != sForm.getAppUser().getUserAccount().getSkuTag()) { String t = sForm.getAppUser().getUserAccount().getSkuTag().getValue(); if (t != null && t.length() > 0) { mSkuTag = t; } } // Display the contact info PdfPTable contactInfo = new PdfPTable(2); contactInfo.setWidthPercentage(50); contactInfo.setWidths(sizes); contactInfo.getDefaultCell().setBorder(borderType); contactInfo.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT); String orderOnlineStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.orderOnLine:", null); contactInfo.addCell(makePhrase(orderOnlineStr + " ", smallHeading, false)); contactInfo.addCell( makePhrase( sForm.getAppUser().getUserStore().getStorePrimaryWebAddress().getValue(), smallHeading, true)); ContactUsInfo contact = null; if (sForm.getAppUser().getContactUsList().size() == 1) { contact = (ContactUsInfo) sForm.getAppUser().getContactUsList().get(0); } String orderFaxNumber = null, bscdesc = null; if (sForm.getAppUser().getSite().getBSC() != null && sForm.getAppUser().getSite().getBSC().getFaxNumber() != null && sForm.getAppUser().getSite().getBSC().getFaxNumber().getPhoneNum() != null) { orderFaxNumber = sForm.getAppUser().getSite().getBSC().getFaxNumber().getPhoneNum(); bscdesc = sForm.getAppUser().getSite().getBSC().getBusEntityData().getLongDesc(); } if (orderFaxNumber == null && contact != null) { orderFaxNumber = contact.getFax(); } if (orderFaxNumber != null) { String faxOrderStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.faxOrder:", null); contactInfo.addCell(makePhrase(faxOrderStr + " ", smallHeading, false)); contactInfo.addCell(makePhrase(orderFaxNumber, smallHeading, true)); } if (null != bscdesc && bscdesc.length() > 0) { // if there is a BSC descripton set, then show // that information. PdfPCell cell = new PdfPCell(new Paragraph(bscdesc, smallHeading)); cell.disableBorderSide(PdfPCell.LEFT); cell.disableBorderSide(PdfPCell.RIGHT); cell.disableBorderSide(PdfPCell.TOP); cell.disableBorderSide(PdfPCell.BOTTOM); cell.setColspan(2); cell.setPaddingTop(6); contactInfo.addCell(cell); } else { // otherwise show the standard contact us information // request for dmsi - dhl for eric. durval 11/1/2005. if (contact != null) { contactInfo.addCell(makePhrase(" ", smallHeading, false)); contactInfo.addCell(makePhrase(" ", smallHeading, true)); String contactUsStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.contactUs", null); contactInfo.addCell(makePhrase(contactUsStr + " ", smallHeading, false)); contactInfo.addCell(makePhrase("", smallHeading, true)); String phoneStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.phone:", null); contactInfo.addCell(makePhrase(phoneStr + " ", smallHeading, false)); contactInfo.addCell( makePhrase( "" + contact.getPhone() + " " + contact.getCallHours(), smallHeading, true)); String emailStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.email:", null); contactInfo.addCell(makePhrase(emailStr + " ", smallHeading, false)); contactInfo.addCell(makePhrase(contact.getEmail(), smallHeading, true)); } } // make the two tables into one PdfPTable wholeTable = new PdfPTable(2); wholeTable.setWidthPercentage(100); wholeTable.setWidths(halves); wholeTable.getDefaultCell().setBorder(borderType); wholeTable.addCell(personalInfo); wholeTable.addCell(contactInfo); document.add(wholeTable); String ogcomments = ""; if (null != sForm.getAppUser().getSite() && null != sForm.getAppUser().getSite().getComments()) { ogcomments = sForm.getAppUser().getSite().getComments().getValue(); } if (null == ogcomments || ogcomments.length() == 0) { if (null != sForm.getAppUser().getUserAccount()) { ogcomments = sForm.getAppUser().getUserAccount().getComments().getValue(); } } // add the comments if there are any if (ogcomments != null && ogcomments.length() > 0) { document.add(makeBlankLine()); String commentsStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.comments:", null); document.add(makePhrase(commentsStr + " " + ogcomments, smallHeading, true)); } document.add(makeBlankLine()); String commentsStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.comments:", null); document.add( makePhrase( commentsStr + " " + "__________________________________________" + "__________________________________________" + "__________", smallHeading, true)); document.add( makePhrase( "__________" + "__________________________________________" + "__________________________________________" + "__________", smallHeading, true)); document.add( makePhrase( "__________" + "__________________________________________" + "__________________________________________" + "__________", smallHeading, true)); // Add an order guide note in the next page if a note is present. if (null != sForm.getAppUser().getUserAccount() && null != sForm.getAppUser().getUserAccount().getOrderGuideNote()) { String t = sForm.getAppUser().getUserAccount().getOrderGuideNote().getValue(); if (t != null && t.length() > 0) { document.newPage(); pageNumber = pageNumber + 1; // document.add(makeBlankLine()); document.add(makePhrase(t, smallHeading, true)); } } PdfPTable sort = new PdfPTable(1); sort.setWidthPercentage(100); sort.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); sort.getDefaultCell().setBorder(borderType); if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) { String sortedByCategoryStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.sortedBy:Category", null); sort.addCell(makePhrase(sortedByCategoryStr + " ", smallHeading, false)); } else if (sForm.getOrderBy() == Constants.ORDER_BY_CUST_SKU) { String sortedByOurSkuNumStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.sortedBy:OurSkuNum", null); sort.addCell(makePhrase(sortedByOurSkuNumStr, smallHeading, false)); } else { String sortedByProductNameStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.sortedBy:ProductName", null); sort.addCell(makePhrase(sortedByProductNameStr, smallHeading, false)); } document.add(sort); }
private void drawHeader( Document document, int pPageNumber, String pSenderName, String pImageName, boolean pInventoryHeader) throws DocumentException { // add the logo try { Image i = Image.getInstance(pImageName); float x = document.leftMargin(); float y = document.getPageSize().getHeight() - i.getHeight() - 5; i.setAbsolutePosition(x, y); document.add(i); } catch (Exception e) { // e.printStackTrace(); } // deal with header info construct the table/cells with all of // the header information must be the pdf specific type or the // table will not use the full width of the page. // unfortuanately this means we are limited to PDF rendering // only. // draw a line XXX this is somewhat of a hack, as there seems // to be no way to draw a line in the current iText API that is // relative to your current position in the document document.add(makeLine()); // add the item header line PdfPTable itemHeader = new PdfPTable(mColumnCount); itemHeader.setWidthPercentage(100); itemHeader.setWidths(itmColumnWidth); itemHeader.getDefaultCell().setBorderWidth(2); itemHeader.getDefaultCell().setBackgroundColor(java.awt.Color.black); itemHeader.getDefaultCell().setHorizontalAlignment(Cell.ALIGN_CENTER); itemHeader.getDefaultCell().setVerticalAlignment(Cell.ALIGN_MIDDLE); itemHeader.getDefaultCell().setBorderColor(java.awt.Color.white); if (!catalogOnly) { String c1 = ""; if (pInventoryHeader) { String qtyOnHandStr = ClwI18nUtil.getMessage(mRequest, "shop.og.table.header.qtyOnHand", null); itemHeader.addCell(makePhrase(qtyOnHandStr, itemHeading, false)); String requestedQtyStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.requestedQty", null); itemHeader.addCell(makePhrase(requestedQtyStr, itemHeading, false)); mForInventoryShopping = true; } else { itemHeader.addCell(makePhrase(" ", itemHeading, false)); if (mForInventoryShopping) { c1 = ClwI18nUtil.getMessage(mRequest, "shop.og.text.requestedQty", null); } else { c1 = ClwI18nUtil.getMessage(mRequest, "shop.og.text.orderQty", null); } itemHeader.addCell(makePhrase(c1, itemHeading, false)); } } if (catalogOnly) { String c1 = ClwI18nUtil.getMessage(mRequest, "shop.og.text.orderQty", null); itemHeader.addCell(makePhrase(c1, itemHeading, false)); } itemHeader.addCell(makePhrase(mSkuTag, itemHeading, false)); String c2 = ""; if (pInventoryHeader) { c2 = ClwI18nUtil.getMessage(mRequest, "shop.og.text.inventoryProductName", null); } else { c2 = ClwI18nUtil.getMessage(mRequest, "shop.og.text.productName", null); } itemHeader.addCell(makePhrase(c2, itemHeading, false)); if (mShowSize) { String sizeStr = ClwI18nUtil.getMessage(mRequest, "shoppingItems.text.size", null); itemHeader.addCell(makePhrase(sizeStr, itemHeading, false)); } /* String packStr = ClwI18nUtil.getMessage(mRequest, "shoppingItems.text.pack", null); itemHeader.addCell(makePhrase(packStr, itemHeading, false)); String uomStr = ClwI18nUtil.getMessage(mRequest, "shoppingItems.text.uom", null); itemHeader.addCell(makePhrase(uomStr, itemHeading, false));*/ CurrencyData curr = ClwI18nUtil.getCurrency(mCatalogLocaleCd); String currencyCode = "CHF"; if (curr != null) { currencyCode = curr.getGlobalCode(); } if (mShowPrice) { String priceStr = ClwI18nUtil.getMessage( mRequest, "shoppingItems.text.priceIn", new String[] {currencyCode}); itemHeader.addCell(makePhrase(priceStr, itemHeading, false)); } if (catalogOnly) { String splStr = ClwI18nUtil.getMessage(mRequest, "shoppingItems.text.spl", null); itemHeader.addCell(makePhrase(splStr, itemHeading, false)); } if (!catalogOnly) { String amountStr = ClwI18nUtil.getMessage( mRequest, "shoppingItems.text.amountIn", new String[] {currencyCode}); itemHeader.addCell(makePhrase(amountStr, itemHeading, false)); } document.add(itemHeader); }
private void setPaint(boolean invert, double xoffset, double yoffset, boolean fill) { if (paint instanceof Color) { Color color = (Color) paint; int alpha = color.getAlpha(); if (fill) { if (alpha != currentFillGState) { currentFillGState = alpha; PdfGState gs = fillGState[alpha]; if (gs == null) { gs = new PdfGState(); gs.setFillOpacity(alpha / 255f); fillGState[alpha] = gs; } cb.setGState(gs); } cb.setColorFill(color); } else { if (alpha != currentStrokeGState) { currentStrokeGState = alpha; PdfGState gs = strokeGState[alpha]; if (gs == null) { gs = new PdfGState(); gs.setStrokeOpacity(alpha / 255f); strokeGState[alpha] = gs; } cb.setGState(gs); } cb.setColorStroke(color); } } else if (paint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) paint; Point2D p1 = gp.getPoint1(); transform.transform(p1, p1); Point2D p2 = gp.getPoint2(); transform.transform(p2, p2); Color c1 = gp.getColor1(); Color c2 = gp.getColor2(); PdfShading shading = PdfShading.simpleAxial( cb.getPdfWriter(), (float) p1.getX(), normalizeY((float) p1.getY()), (float) p2.getX(), normalizeY((float) p2.getY()), c1, c2); PdfShadingPattern pat = new PdfShadingPattern(shading); if (fill) cb.setShadingFill(pat); else cb.setShadingStroke(pat); } else if (paint instanceof TexturePaint) { try { TexturePaint tp = (TexturePaint) paint; BufferedImage img = tp.getImage(); Rectangle2D rect = tp.getAnchorRect(); com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null); PdfPatternPainter pattern = cb.createPattern(image.getWidth(), image.getHeight()); AffineTransform inverse = this.normalizeMatrix(); inverse.translate(rect.getX(), rect.getY()); inverse.scale(rect.getWidth() / image.getWidth(), -rect.getHeight() / image.getHeight()); double[] mx = new double[6]; inverse.getMatrix(mx); pattern.setPatternMatrix( (float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4], (float) mx[5]); image.setAbsolutePosition(0, 0); pattern.addImage(image); if (fill) cb.setPatternFill(pattern); else cb.setPatternStroke(pattern); } catch (Exception ex) { if (fill) cb.setColorFill(Color.gray); else cb.setColorStroke(Color.gray); } } else { try { BufferedImage img = null; int type = BufferedImage.TYPE_4BYTE_ABGR; if (paint.getTransparency() == Transparency.OPAQUE) { type = BufferedImage.TYPE_3BYTE_BGR; } img = new BufferedImage((int) width, (int) height, type); Graphics2D g = (Graphics2D) img.getGraphics(); g.transform(transform); AffineTransform inv = transform.createInverse(); Shape fillRect = new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()); fillRect = inv.createTransformedShape(fillRect); g.setPaint(paint); g.fill(fillRect); if (invert) { AffineTransform tx = new AffineTransform(); tx.scale(1, -1); tx.translate(-xoffset, -yoffset); g.drawImage(img, tx, null); } g.dispose(); g = null; com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null); PdfPatternPainter pattern = cb.createPattern(width, height); image.setAbsolutePosition(0, 0); pattern.addImage(image); if (fill) cb.setPatternFill(pattern); else cb.setPatternStroke(pattern); } catch (Exception ex) { if (fill) cb.setColorFill(Color.gray); else cb.setColorStroke(Color.gray); } } }
public void insertImageRubrica(PdfReader reader, int pageCount, String fileWrite) { int iniY = 841 - 10; int iniX = 595 - 10; try { // Verificar qual � a imagem para utilizar na rubrica Image img = null; if (LoadImageAction.rubimgSameass) img = LoadImageAction.getAssImagePDF(); else img = LoadImageAction.getRubImagePDF(); // Criar Modelo para as Rubricas ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper stp1 = new PdfStamper(reader, out, '\3', true); PdfFormField sig = PdfFormField.createSignature(stp1.getWriter()); if (LoadImageAction.posRubSame) { int[] coord = LoadImageAction.getImageXY(); if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample coord[0] = LoadImageAction.getAssX(); coord[1] = LoadImageAction.getAssY(); } sig.setWidget( new Rectangle( coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()), null); } else { sig.setWidget( new Rectangle(iniX - img.getWidth(), iniY - img.getHeight(), iniX, iniY), null); } sig.setFlags(PdfAnnotation.FLAGS_PRINT); sig.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g")); sig.setFieldName("Assinaturas"); sig.setPage(1); // Se a imagem da rubrica n for a mesma da assinatura n�o mete na ultima pag if (!LoadImageAction.rubimgSameass) pageCount = pageCount - 1; // Inserir em todas as paginas o Modelo for (int i = 1; i <= pageCount; i++) stp1.addAnnotation(sig, i); stp1.close(); // Guardar/Ler PDF com modelos inseridos reader = new PdfReader(out.toByteArray()); File outputFile = new File(fileWrite); // Preencher Modelo com Dados PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setAcro6Layers(true); reader.close(); sap.setVisibleSignature("Assinaturas"); sap.setLayer2Text("\n\n(Doc. assinado digitalmente)"); sap.setImage(img); PdfSignature dic = new PdfSignature( PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$ dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); int contentEstimated = 15000; HashMap<Object, Object> exc = new HashMap<Object, Object>(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); Provider prov = entry.getProvider(); PrivateKey key = entry.getPrivateKey(); Certificate[] chain = entry.getCertificateChain(); PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false); // $NON-NLS-1$ InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$ byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (isUseOCSP() && chain.length >= 2) { String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (url != null && url.length() > 0) ocsp = new OcspClientBouncyCastle( (X509Certificate) chain[0], (X509Certificate) chain[1], url) .getEncoded(); } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClient tsc = null; if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) throw new Exception("Not enough space"); // $NON-NLS-1$ byte[] paddedSig = new byte[contentEstimated]; PdfDictionary dic2 = new PdfDictionary(); System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); } catch (Exception e) { e.printStackTrace(); } }
public String hashSignExternalTimestamp(String read, String write) throws Exception { Provider prov = entry.getProvider(); PrivateKey key = entry.getPrivateKey(); Certificate[] chain = entry.getCertificateChain(); PdfReader reader = new PdfReader(read); int pageCount = reader.getNumberOfPages(); File outputFile = new File(write); PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setProvider(prov.getName()); sap.setReason(getReason()); sap.setLocation(getLocation()); sap.setContact(getContact()); sap.setCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); int[] coord = LoadImageAction.getImageXY(); if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample coord[0] = LoadImageAction.getAssX(); coord[1] = LoadImageAction.getAssY(); } // Adicionar imagem ao PDF se for para utilizar if (!isSignatureVisible()) { sap.setLayer2Text(""); } else { if (LoadImageAction.getFlagPDF()) { sap.setAcro6Layers(true); Image img = LoadImageAction.getAssImagePDF(); if (LoadImageAction.getPagToSign() == -1) sap.setVisibleSignature( new Rectangle( coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()), pageCount, null); else sap.setVisibleSignature( new Rectangle( coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()), LoadImageAction.getPagToSign(), null); sap.setLayer2Text("\n\n(Doc. assinado digitalmente)"); sap.setImage(img); } else { if (LoadImageAction.getPagToSign() == -1) sap.setVisibleSignature( new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40), pageCount, null); else sap.setVisibleSignature( new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40), LoadImageAction.getPagToSign(), null); sap.setLayer2Text(getSignatureText((X509Certificate) chain[0], sap.getSignDate())); } } PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$ dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); int contentEstimated = 15000; HashMap<Object, Object> exc = new HashMap<Object, Object>(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false); InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$ byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (isUseOCSP() && chain.length >= 2) { String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (url != null && url.length() > 0) ocsp = new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url) .getEncoded(); } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClient tsc = null; if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation); // o PIN/PASS dos certificados � pedido aqui byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) throw new Exception("Not enough space"); // $NON-NLS-1$ byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); deleteFile(read); return write; }