List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:androidGLUESigner.pdf.PDFSigExtractor.java
License:Open Source License
/** * extracts the signature field for previewing. * @throws IOException /* ww w.jav a 2 s .c o m*/ */ public static ArrayList<SignatureInfo> getSignatureInfo(String inputPath) { PdfReader reader; try { reader = new PdfReader(inputPath); } catch (IOException e) { return new ArrayList<SignatureInfo>(); } AcroFields af = reader.getAcroFields(); ArrayList names = af.getSignatureNames(); ArrayList<SignatureInfo> signatures = new ArrayList<SignatureInfo>(); // For every signature : for (int k = 0; k < names.size(); ++k) { String name = (String) names.get(k); SignatureInfo sigInfo = new SignatureInfo(); // get coordinates float[] position = af.getFieldPositions(name); // page number float page = position[0]; // left float llx = position[1]; // bottom float lly = position[2]; // right float urx = position[3]; // top float ury = position[4]; // get size of pdf page Rectangle size = reader.getPageSize((int) page); float height = size.getHeight(); // subtract height to translate to Android canvas coordinate system lly = height - lly; ury = height - ury; float ulx = llx; // create a Rectangle from obtained signature field coordinates Rect sigRect = new Rect((int) ulx, (int) ury, (int) urx, (int) lly); sigInfo.setGraphicRect(sigRect, 1.0f); // obtain additional information like reason, location, ... PdfDictionary sig = af.getSignatureDictionary(name); sigInfo.setSignatureName(sig.getAsString(PdfName.NAME).toString()); sigInfo.setSignatureLocation(sig.getAsString(PdfName.LOCATION).toString()); sigInfo.setSignatureReason(sig.getAsString(PdfName.REASON).toString()); sigInfo.setSignatureType(SignatureType.NORMAL); sigInfo.setPageNumber((int) page); // add new signature information to signatures signatures.add(sigInfo); } return signatures; }
From source file:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Prepare the signing of the pdf (siganture appearance, placeholders, sigimage, ..) * @param inputStream the stream to the input pdf file * @param outputStream the stream to the output pdf file * @return hash value with ocsp included * @throws IOException// w w w.j a v a 2 s . c o m * @throws DocumentException * @throws GeneralSecurityException */ public byte[] prepareSign(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException, GeneralSecurityException { PdfReader reader = new PdfReader(inputStream); PdfStamper stp = PdfStamper.createSignature(reader, outputStream, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, getCertificateChain(), null, PdfSignatureAppearance.WINCER_SIGNED); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(siginfo.getSignatureReason()); dic.setLocation(siginfo.getSignatureLocation()); dic.setName(siginfo.getSignatureName()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } // preserve some space for the contents HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(SIGNATURE_MAX_SIZE * 2 + 2)); sap.preClose(exc); // Save placeholder which will be replaced with actual signature later byte[] placeHolder = getPlaceHolderArr(SIGNATURE_MAX_SIZE * 2); // Replace the contents PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(placeHolder).setHexWriting(true)); sap.close(dic2); // Calculate the digest InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } hash = messageDigest.digest(); calendar = Calendar.getInstance(); ocsp = ocspRequest(cert, issuerCert); System.out.println("Got OCSP response, length = " + ocsp.length); // Calculate another digest over authenticatedAttributes PdfPKCS7 sgn = new PdfPKCS7(null, getCertificateChain(), null, hashAlgo, null, true); byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, calendar, ocsp); return sh; }
From source file:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Simple Sign method to create a signature without Online Timestamp (needed if device * has no internet connection)/*w ww . j a v a2 s . c o m*/ * * @param inputfile the inputfile * @param outputfile the outpuftile * @param connection the IConnection Object */ public void simpleSign(String inputfile, String outputfile, IConnection connection) throws IOException, DocumentException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, ReaderException { try { SignatureInfo sigInfo = getSiginfo(); PdfReader reader = new PdfReader(inputfile); FileOutputStream fout = new FileOutputStream(outputfile); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, new Certificate[] { getCertificateChain()[0] }, null, PdfSignatureAppearance.SELF_SIGNED); sap.setReason(sigInfo.getSignatureReason()); sap.setLocation(sigInfo.getSignatureLocation()); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } sap.setExternalDigest(new byte[256], new byte[20], null); sap.preClose(); java.io.InputStream inp = sap.getRangeStream(); byte bytesToHash[] = IOUtils.toByteArray(inp); // sign the hash value byte[] signed = connection.sign(bytesToHash); PdfPKCS7 pdfSignature = sap.getSigStandard().getSigner(); pdfSignature.setExternalDigest(signed, null, "RSA"); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.CONTENTS, new PdfString(pdfSignature.getEncodedPKCS1()).setHexWriting(true)); sap.close(dic); } catch (Exception e) { Logger.toConsole(e); } }
From source file:br.com.nordestefomento.jrimum.bopepo.view.guia.ViewerPDF.java
License:Apache License
/** * <p>/*from ww w. j a v a 2 s. com*/ * SOBRE O MTODO * </p> * * @throws IOException * @throws DocumentException * * @since */ private void inicializar() throws IOException, DocumentException { if (isTemplateFromResource()) { reader = new PdfReader(getTemplateFromResource()); } else { reader = new PdfReader(getTemplate().getAbsolutePath()); } outputStream = new ByteArrayOutputStream(); stamper = new PdfStamper(reader, outputStream); form = stamper.getAcroFields(); }
From source file:br.com.nordestefomento.jrimum.utilix.PDFUtil.java
License:Apache License
/** * <p>// ww w . j av a 2 s. c o m * Junta varios arquivos pdf em um soh. * </p> * * @param pdfFiles * Lista de array de bytes * * @return Arquivo PDF em forma de byte * @since 0.2 */ @SuppressWarnings("unchecked") public static byte[] mergeFiles(List<byte[]> pdfFiles) { // retorno byte[] bytes = null; if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) { int pageOffset = 0; boolean first = true; ArrayList master = null; Document document = null; PdfCopy writer = null; ByteArrayOutputStream byteOS = null; try { byteOS = new ByteArrayOutputStream(); master = new ArrayList(); for (byte[] doc : pdfFiles) { if (isNotNull(doc)) { // cria-se um reader para cada documento PdfReader reader = new PdfReader(doc); if (reader.isEncrypted()) { reader = new PdfReader(doc, "".getBytes()); } reader.consolidateNamedDestinations(); // pega-se o numero total de paginas int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (isNotNull(bookmarks)) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += n; if (first) { // passo 1: criar um document-object document = new Document(reader.getPageSizeWithRotation(1)); // passo 2: criar um writer que observa o documento writer = new PdfCopy(document, byteOS); document.addAuthor("JRimum Group"); document.addSubject("JRimum Merged Document"); document.addCreator("JRimum Utilix"); // passo 3: abre-se o documento document.open(); first = false; } // passo 4: adciona-se o conteudo PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } } } if (master.size() > 0) { writer.setOutlines(master); } // passo 5: fecha-se o documento if (isNotNull(document)) { document.close(); } bytes = byteOS.toByteArray(); } catch (Exception e) { LOG.error("", e); } } return bytes; }
From source file:br.gov.jfrj.itextpdf.Documento.java
License:Open Source License
public static int getNumberOfPages(byte[] abPdf) throws IOException { final PdfReader reader = new PdfReader(abPdf); final int n = reader.getNumberOfPages(); reader.close();//ww w . j a v a 2 s . c o m return n; }
From source file:br.gov.jfrj.itextpdf.Documento.java
License:Open Source License
public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito, boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal, Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException { PdfReader pdfIn = new PdfReader(abPdf); Document doc = new Document(PageSize.A4, 0, 0, 0, 0); // final SimpleDateFormat sdf = new SimpleDateFormat( // "EEE MMM dd HH:mm:ss zzz yyyy"); // doc.add(new Meta("creationdate", sdf.format(new Date(0L)))); final ByteArrayOutputStream boA4 = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(doc, boA4); doc.open();//from ww w .ja va 2s . c o m PdfContentByte cb = writer.getDirectContent(); // Resize every page to A4 size // // double thetaRotation = 0.0; for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) { int rot = pdfIn.getPageRotation(i); float left = pdfIn.getPageSize(i).getLeft(); float bottom = pdfIn.getPageSize(i).getBottom(); float top = pdfIn.getPageSize(i).getTop(); float right = pdfIn.getPageSize(i).getRight(); PdfImportedPage page = writer.getImportedPage(pdfIn, i); float w = page.getWidth(); float h = page.getHeight(); // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w // + ", " + h); doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4); doc.newPage(); cb.saveState(); if (rot != 0 && rot != 180) { float swap = w; w = h; h = swap; } float pw = doc.getPageSize().getWidth(); float ph = doc.getPageSize().getHeight(); double scale = Math.min(pw / w, ph / h); // do my transformations : cb.transform(AffineTransform.getScaleInstance(scale, scale)); if (!internoProduzido) { cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN)); cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN)); } if (rot != 0) { double theta = -rot * (Math.PI / 180); if (rot == 180) { cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2)); } else { cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2)); } if (rot == 90) { cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2)); } else if (rot == 270) { cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2)); } } // Logger.getRootLogger().error( // "----- dimensoes: " + rot + ", " + w + ", " + h); // Logger.getRootLogger().error("----- page: " + pw + ", " + ph); // cb.transform(AffineTransform.getTranslateInstance( // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2)); // put the page cb.addTemplate(page, 0, 0); // draw a red rectangle at the page borders // // cb.saveState(); // cb.setColorStroke(Color.red); // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i) // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn // .getPageSize(i).getTop()); // cb.stroke(); // cb.restoreState(); cb.restoreState(); } doc.close(); abPdf = boA4.toByteArray(); final ByteArrayOutputStream bo2 = new ByteArrayOutputStream(); final PdfReader reader = new PdfReader(abPdf); final int n = reader.getNumberOfPages(); final PdfStamper stamp = new PdfStamper(reader, bo2); // adding content to each page int i = 0; PdfContentByte under; PdfContentByte over; final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false); // Image img = Image.getInstance("watermark.jpg"); final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); byte maskr[] = { (byte) 0xff }; Image mask = Image.getInstance(1, 1, 1, 1, maskr); mask.makeMask(); mask.setInverted(true); while (i < n) { i++; // watermark under the existing page under = stamp.getUnderContent(i); over = stamp.getOverContent(i); final Barcode39 code39 = new Barcode39(); // code39.setCode(doc.getCodigo()); code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", "")); code39.setStartStopText(false); final Image image39 = code39.createImageWithBarcode(over, null, null); Rectangle r = stamp.getReader().getPageSizeWithRotation(i); image39.setInitialRotation((float) Math.PI / 2.0f); image39.setAbsolutePosition( r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT, BARCODE_HEIGHT_IN_CM * CM_UNIT); image39.setBackgroundColor(Color.green); image39.setBorderColor(Color.RED); image39.setBorderWidth(0.5f * CM_UNIT); image39.setImageMask(mask); over.setRGBColorFill(255, 255, 255); mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT, (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT); mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT, image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT); over.addImage(mask); over.setRGBColorFill(0, 0, 0); over.addImage(image39); // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0, // mask.getScaledHeight() * 8, 100, 450); if (qrCode != null) { java.awt.Image imgQRCode = createQRCodeImage(qrCode); Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true); imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT); imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT); over.setRGBColorFill(255, 255, 255); mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT, (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT); mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT, (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT); over.addImage(mask); over.setRGBColorFill(0, 0, 0); over.addImage(imageQRCode); } if (mensagem != null) { PdfPTable table = new PdfPTable(1); table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT); PdfPCell cell = new PdfPCell(new Paragraph(mensagem, FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK))); cell.setBorderWidth(0); table.addCell(cell); over.setRGBColorFill(255, 255, 255); mask.setAbsolutePosition( (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT, (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT); mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(), 2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight()); over.addImage(mask); over.setRGBColorFill(0, 0, 0); table.writeSelectedRows(0, -1, (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT, table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over); } if (cancelado) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } else if (rascunho) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } else if (semEfeito) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } // if (!rascunho // && request.getRequestURL().indexOf("http://laguna/") == -1) { if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false")) || (!Contexto.resource("isBaseTest").equals("false")))) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } // Imprime um circulo com o numero da pagina dentro. if (paginaInicial != null) { String sFl = String.valueOf(paginaInicial + i - 1); // Se for a ultima pagina e o numero nao casar, acrescenta "-" e // pagina final if (n == i) { if (paginaFinal != paginaInicial + n - 1) { sFl = sFl + "-" + String.valueOf(paginaFinal); } } if (i > cOmitirNumeracao) { // Raio do circulo interno final float radius = 18f; // Distancia entre o circulo interno e o externo final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT), helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT)) - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT), helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT)) + 2 * TEXT_TO_CIRCLE_INTERSPACE; // Centro do circulo float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace); float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace); over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(1f); over.setGState(gs); over.setColorFill(Color.BLACK); over.saveState(); over.setColorStroke(Color.black); over.setLineWidth(1f); over.setColorFill(Color.WHITE); // Circulo externo over.circle(xCenter, yCenter, radius + circleInterspace); over.fill(); over.circle(xCenter, yCenter, radius + circleInterspace); over.stroke(); // Circulo interno over.circle(xCenter, yCenter, radius); over.stroke(); over.restoreState(); { over.saveState(); over.beginText(); over.setFontAndSize(helv, TEXT_HEIGHT); // Escreve o texto superior do carimbo float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT); showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter, radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true); // Escreve o texto inferior float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT); showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter, radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false); over.endText(); over.restoreState(); } over.beginText(); int textHeight = 23; // Diminui o tamanho do font ate que o texto caiba dentro do // circulo interno while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE))) textHeight--; float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight); over.setFontAndSize(helv, textHeight); over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0); over.endText(); over.restoreState(); } } } stamp.close(); return bo2.toByteArray(); }
From source file:br.gov.jfrj.itextpdf.Documento.java
License:Open Source License
public static byte[] getDocumento(ExMobil mob, ExMovimentacao mov, boolean completo, boolean estampar, String hash, byte[] certificado) throws Exception { final ByteArrayOutputStream bo2 = new ByteArrayOutputStream(); PdfReader reader;//w ww . ja v a 2 s .co m int n; int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; Document document = null; PdfCopy writer = null; int nivelInicial = 0; // if (request.getRequestURI().indexOf("/completo/") == -1) { // return getPdf(docvia, mov != null ? mov : docvia.getExDocumento(), // mov != null ? mov.getNumVia() : docvia.getNumVia(), null, // null, request); // } List<ExArquivoNumerado> ans = mob.filtrarArquivosNumerados(mov, completo); if (!completo && !estampar && ans.size() == 1) { if (certificado != null) { CdService cdService = Service.getCdService(); return cdService.produzPacoteAssinavel(certificado, null, ans.get(0).getArquivo().getPdf(), true, ExDao.getInstance().getServerDateTime()); } else if (hash != null) { // Calcula o hash do documento String alg = hash; MessageDigest md = MessageDigest.getInstance(alg); md.update(ans.get(0).getArquivo().getPdf()); return md.digest(); } else { return ans.get(0).getArquivo().getPdf(); } } try { for (ExArquivoNumerado an : ans) { // byte[] ab = getPdf(docvia, an.getArquivo(), an.getNumVia(), // an // .getPaginaInicial(), an.getPaginaFinal(), request); String sigla = mob.getSigla(); if (an.getArquivo() instanceof ExMovimentacao) { ExMovimentacao m = (ExMovimentacao) an.getArquivo(); if (m.getExTipoMovimentacao().getId() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA) sigla = m.getExMobil().getSigla(); } else { sigla = an.getMobil().getSigla(); } byte[] ab = !estampar ? an.getArquivo().getPdf() : stamp(an.getArquivo().getPdf(), sigla, an.getArquivo().isRascunho(), an.getArquivo().isCancelado(), an.getArquivo().isSemEfeito(), an.getArquivo().isInternoProduzido(), an.getArquivo().getQRCode(), an.getArquivo().getMensagem(), an.getPaginaInicial(), an.getPaginaFinal(), an.getOmitirNumeracao(), SigaExProperties.getTextoSuperiorCarimbo(), mob.getExDocumento().getOrgaoUsuario().getDescricao()); // we create a reader for a certain document reader = new PdfReader(ab); reader.consolidateNamedDestinations(); // we retrieve the total number of pages n = reader.getNumberOfPages(); // List bookmarks = SimpleBookmark.getBookmark(reader); // master.add(new Bookmark) // if (bookmarks != null) { // if (pageOffset != 0) // SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, // null); // master.addAll(bookmarks); // } if (f == 0) { // step 1: creation of a document-object document = new Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the // document writer = new PdfCopy(document, bo2); writer.setFullCompression(); // writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); // step 3: we open the document document.open(); nivelInicial = an.getNivel(); } // PdfOutline root = writer.getDirectContent().getRootOutline(); // PdfContentByte cb = writer.getDirectContent(); // PdfDestination destination = new // PdfDestination(PdfDestination.FITH, position); // step 4: we add content PdfImportedPage page; for (int j = 0; j < n;) { ++j; page = writer.getImportedPage(reader, j); writer.addPage(page); if (j == 1) { // PdfContentByte cb = writer.getDirectContent(); // PdfOutline root = cb.getRootOutline(); // PdfOutline oline1 = new PdfOutline(root, // PdfAction.gotoLocalPage("1", false),"Chapter 1"); HashMap map = new HashMap(); map.put("Title", an.getNome()); map.put("Action", "GoTo"); map.put("Page", j + pageOffset + ""); map.put("Kids", new ArrayList()); ArrayList mapPai = master; for (int i = 0; i < an.getNivel() - nivelInicial; i++) { mapPai = ((ArrayList) ((HashMap) mapPai.get(mapPai.size() - 1)).get("Kids")); } mapPai.add(map); } } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); pageOffset += n; f++; } if (!master.isEmpty()) writer.setOutlines(master); // PdfDictionary info = writer.getInfo(); // info.put(PdfName.MODDATE, null); // info.put(PdfName.CREATIONDATE, null); // info.put(PdfName.ID, null); document.close(); } catch (Exception e) { e.printStackTrace(); } return bo2.toByteArray(); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void main(String[] args) throws Exception { byte[] pdf;/*from w w w . j a v a2 s . c o m*/ { File f = new File("c:/trabalhos/java/teste.pdf"); FileInputStream fin = new FileInputStream(f); pdf = new byte[(int) f.length()]; fin.read(pdf); fin.close(); } PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 256000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.setSignDate(Calendar.getInstance()); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); byte[] signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception { PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 128000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG);/*from w w w. j av a 2 s. co m*/ dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }