List of usage examples for com.itextpdf.text.pdf PdfReader PdfReader
public PdfReader(final PdfReader reader)
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfSplitDropCopy(File[] files) throws IOException, DocumentException { // TODO Instead of hard code path, pass in as argument String path;/*from ww w.j a va 2s . c o m*/ path = files[0].getParent(); File[] listOfFiles = files; /* Stores the listing of the files */ System.out.println(directoryField); for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; } // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); String[] fileNameNum = fileNameWithoutExt.split("-"); int fileNameNumOne = Integer.parseInt(fileNameNum[0]); int fileNameNumTwo = Integer.parseInt(fileNameNum[1]); int constant = 1; int numPages = fileNameNumTwo - fileNameNumOne; PdfReader pdfFileReader = new PdfReader(file.getPath()); Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); ; /* instantiates a new document to be made */ // Determine number of pages by difference of lot numbers // Read in the source document // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf // Create a copy of the orignal source file. We will pick specific pages out below for (int j = 0; j < numPages + 1; j++) { String FileName = fileNameWithoutExt; /* Dynamic file name */ PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf")); document.open(); copy.addPage( copy.getImportedPage(pdfFileReader, constant)); /* Import pages from original document */ if (j == 1) { newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } else if (j > 1) { newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } document.close(); } pdfFileReader.close(); } }
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfSplitDropSupplierDoc(File[] files) throws IOException, DocumentException { // TODO Instead of hard code path, pass in as argument String path;// w ww .j a va 2 s.c o m if (directoryField.getText().isEmpty() || directoryField.getText().equals(example)) { path = files[0].getParent(); } else { path = directoryField.getText(); } File[] listOfFiles = files; /* Stores the listing of the files */ for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; } // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); System.out.println(fileNameWithoutExt); PdfReader pdfFileReader = new PdfReader(file.getPath()); Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); /* instantiates a new document to be made */ // Determine number of pages by difference of lot numbers // Read in the source document // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf // Create a copy of the orignal source file. We will pick specific pages out below // Split on a space '\s' String[] fileNames = fileNameWithoutExt.split("-"); String fileNameFirst = fileNames[1]; String fileNameSecond = fileNames[2]; System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond); // Project num is always the 1st part String projectNum = fileNames[0]; if (!projectNum.equals(fileNames[0])) { throw new RuntimeException("Filename needs to be renamed to the correct format"); } // Strip off the first and second lot number, parse into integers int firstLotNum; int secondLotNum; firstLotNum = Integer.parseInt(fileNameFirst); secondLotNum = Integer.parseInt(fileNameSecond); int numPages = secondLotNum - firstLotNum; // Create a copy of the orignal source file. We will pick specific pages out below document.open(); for (int j = 1; j < numPages + 1; j++) { String FileName = projectNum + "-" + (firstLotNum) + ".pdf"; /* Dynamic file name */ firstLotNum++; document = new Document(PageSize.LETTER, 0, 0, 0, 0); PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName)); document.open(); copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */ if (j == 1) { newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } else if (j > 1) { newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n"); } document.close(); } } }
From source file:com.tommontom.pdfsplitter.PdfSplit.java
public void pdfEven(String path) throws IOException, DocumentException { String DEFAULT_PATH = path; // TODO Instead of hard code path, pass in as argument File folder = new File(DEFAULT_PATH); FileNameFilter FileFilter = new FileNameFilter(); File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */ for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; if (!file.isFile()) { continue; }//from ww w . j av a 2 s .co m // Split the source filename into its 2 parts String fileName = file.getName(); String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); // Split on a space '\s' String[] fileNames = fileNameWithoutExt.split("\\s"); if (fileNames.length != 2) { throw new RuntimeException("File name format is not in right format"); } String fileNameFirst = fileNames[0]; String fileNameSecond = fileNames[1]; System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond); String[] fileNameFirstParts = fileNameFirst.split("-"); String[] fileNameSecondParts = fileNameSecond.split("-"); // Project num is always the 1st part String projectNum = fileNameFirstParts[0]; if (!projectNum.equals(fileNameSecondParts[0])) { throw new RuntimeException("Filename needs to be renamed to the correct format"); } // Strip off the first and second lot number, parse into integers int firstLotNum; int secondLotNum; firstLotNum = Integer.parseInt(fileNameFirstParts[1]); secondLotNum = Integer.parseInt(fileNameSecondParts[1]); // Determine number of pages by difference of lot numbers // Read in the source document // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf PdfReader pdfFileReader = new PdfReader(file.getPath()); int mod = pdfFileReader.getNumberOfPages() % 2; if (pdfFileReader.equals(mod)) { throw new RuntimeException("File is not an even number of pages"); } Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); /* instantiates a new document to be made */ int numPages = secondLotNum - firstLotNum + 1; int p = 0; int j = 1; // Create a copy of the orignal source file. We will pick specific pages out below document.open(); while (j < numPages) { j++; if (j % 2 == 1) { j += 1; } firstLotNum++; String FileName = projectNum + "-" + (firstLotNum - 1) + ".pdf"; /* Dynamic file name */ document = new Document(PageSize.LETTER, 0, 0, 0, 0); PdfCopy copy = new PdfCopy(document, new FileOutputStream(DEFAULT_PATH + "//" + FileName)); if (j == 1) { newFileListing = ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n"); } else if (j > 1) { newFileListing += ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n"); } document.open(); p += 2; copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */ copy.addPage(copy.getImportedPage(pdfFileReader, p)); document.close(); } System.out.println("Number of Documents Created:" + numPages); System.out.println("Number of Documents Created:" + listOfFiles[i]); } }
From source file:com.vectorprint.report.itext.SigningOutputStream.java
License:Open Source License
@Override public void secondPass(InputStream firstPass, OutputStream orig) throws IOException { PdfReader reader = null;//from www. j av a2 s .co m try { reader = new PdfReader(firstPass); PdfStamper stamper = PdfStamper.createSignature(reader, orig, '\0'); outer.getDocumentStyler().configureVisualSignature(stamper.getSignatureAppearance()); stamper.close(); } catch (DocumentException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | VectorPrintException ex) { throw new VectorPrintRuntimeException(ex); } finally { if (reader != null) { reader.close(); } } }
From source file:com.vectorprint.report.itext.TocOutputStream.java
License:Open Source License
@Override public void secondPass(InputStream firstPass, OutputStream orig) throws IOException { PdfReader reader = null;/* w w w . j ava2 s . com*/ VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument(); try { reader = new PdfReader(firstPass); prepareToc(); // init fresh components for second pass styling StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance(); StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings()); _stylerFactory.setLayerManager(outer.getElementProducer()); _stylerFactory.setImageLoader(outer.getElementProducer()); outer.getStyleHelper().setStylerFactory(_stylerFactory); EventHelper event = outer.getEventHelper().getClass().newInstance(); event.setItextStylerFactory(_stylerFactory); event.setElementProvider(outer.getElementProducer()); ((DefaultElementProducer) outer.getElementProducer()).setPh(event); Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper()); PdfWriter w = PdfWriter.getInstance(d, orig); w.setPageEvent(event); outer.getStyleHelper().setVpd((VectorPrintDocument) d); _stylerFactory.setDocument(d, w); DocumentStyler ds = _stylerFactory.getDocumentStyler(); outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds)); d.open(); ds.styleAfterOpen(d, null); List outline = SimpleBookmark.getBookmark(reader); if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) { printToc(d, w, vpd); if (outline != null) { int cur = w.getCurrentPageNumber(); SimpleBookmark.shiftPageNumbers(outline, cur, null); } d.newPage(); } outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString()); for (int p = 1; p <= reader.getNumberOfPages(); p++) { Image page = Image.getInstance(w.getImportedPage(reader, p)); page.setAbsolutePosition(0, 0); d.setPageSize(page); d.newPage(); Chunk i = new Chunk(" "); if (vpd.getToc().containsKey(p)) { Section s = null; for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) { if (e.getKey() == p) { s = e.getValue().get(0); break; } } i.setLocalDestination(s.getTitle().getContent()); } d.add(i); w.getDirectContent().addImage(page); w.freeReader(reader); } if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) { printToc(d, w, vpd); } w.setOutlines(outline); if (outer.isWasDebug()) { event.setLastPage(outer.getWriter().getCurrentPageNumber()); d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210))); d.setMargins(5, 5, 5, 5); d.newPage(); outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString()); event.setDebugHereAfter(true); DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory); } d.close(); } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) { throw new VectorPrintRuntimeException(ex); } finally { if (reader != null) { reader.close(); } } }
From source file:com.wabacus.system.assistant.PdfAssistant.java
License:Open Source License
private ByteArrayOutputStream showReportOneRowDataOnPdf(ReportRequest rrequest, Map<String, AbsReportType> mReportTypeObjs, IComponentConfigBean ccbean, PDFExportBean pdfbean, int rowidx) throws Exception { PdfReader pdfTplReader = null;//from www .j ava2 s .co m InputStream istream = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { istream = WabacusAssistant.getInstance().readFile(pdfbean.getPdftemplate()); if (istream == null) return null; pdfTplReader = new PdfReader(new BufferedInputStream(istream)); PdfStamper stamp = new PdfStamper(pdfTplReader, baos); /* ?? */ AcroFields form = stamp.getAcroFields(); form.addSubstitutionFont(bfChinese); boolean flag = true; if (pdfbean != null && pdfbean.getInterceptorObj() != null) { flag = pdfbean.getInterceptorObj().beforeDisplayPdfPageWithTemplate(ccbean, mReportTypeObjs, rowidx, stamp); } if (flag) { Map<String, Item> mFields = form.getFields(); if (mFields != null) { String fieldValueTmp = null; for (String fieldNameTmp : mFields.keySet()) { fieldValueTmp = getPdfFieldValueByName(rrequest, mReportTypeObjs, ccbean, fieldNameTmp, rowidx);//? if (pdfbean != null && pdfbean.getInterceptorObj() != null) { fieldValueTmp = pdfbean.getInterceptorObj().beforeDisplayFieldWithTemplate(ccbean, mReportTypeObjs, rowidx, stamp, fieldNameTmp, fieldValueTmp); } if (fieldValueTmp != null) form.setField(fieldNameTmp, fieldValueTmp); } } } if (pdfbean != null && pdfbean.getInterceptorObj() != null) { pdfbean.getInterceptorObj().afterDisplayPdfPageWithTemplate(ccbean, mReportTypeObjs, rowidx, stamp); } stamp.setFormFlattening(true); stamp.close(); } finally { try { if (istream != null) istream.close(); } catch (IOException e) { e.printStackTrace(); } if (pdfTplReader != null) pdfTplReader.close(); } return baos; }
From source file:com.wabacus.system.assistant.PdfAssistant.java
License:Open Source License
public void addPdfPageToDocument(PdfCopy pdfCopy, ByteArrayOutputStream baos) { if (baos == null) return;/* w ww.j a v a 2s .com*/ PdfReader readerTmp = null; try { readerTmp = new PdfReader(baos.toByteArray()); for (int i = 1, len = readerTmp.getNumberOfPages(); i <= len; i++) { pdfCopy.addPage(pdfCopy.getImportedPage(readerTmp, i)); } } catch (Exception e) { throw new WabacusRuntimeException("PDF", e); } finally { try { if (baos != null) baos.close(); } catch (IOException e) { e.printStackTrace(); } readerTmp.close(); } }
From source file:com.whty.transform.common.utils.TransformUtils.java
public static boolean pdfTopdf(String docpath) { File pdfPath = new File(SysConf.getString("path.output") + docpath + "/pdf/"); if (!pdfPath.exists()) { pdfPath.mkdirs();/*from w ww.ja va2 s .c o m*/ } // pdf? try { PdfReader reader = new PdfReader(SysConf.getString("path.input") + docpath); com.itextpdf.text.Document document = new com.itextpdf.text.Document(reader.getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdfPath.getAbsoluteFile() + "/" + transFileName + ".pdf")); document.open(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, i); copy.addPage(page); } document.close(); return true; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (DocumentException e) { LOGGER.error(e.getMessage(), e); } return false; }
From source file:commentextractor.CommentExtractorApp.java
License:GNU General Public License
static String extractComments(String filename, int first, int last) { StringBuffer output = null;//from w w w . j a v a 2 s.c o m try { PdfReader reader = new PdfReader(filename); if (last >= reader.getNumberOfPages() || (last == -1)) { last = reader.getNumberOfPages(); } output = new StringBuffer(1024); for (int i = first; i <= last; i++) { PdfDictionary page = reader.getPageN(i); PdfArray annotsArray = null; if (page.getAsArray(PdfName.ANNOTS) == null) { continue; } annotsArray = page.getAsArray(PdfName.ANNOTS); for (ListIterator<PdfObject> iter = annotsArray.listIterator(); iter.hasNext();) { PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(iter.next()); PdfString content = (PdfString) PdfReader.getPdfObject(annot.get(PdfName.CONTENTS)); if (content != null) { output.append("----------\n"); output.append("Page " + i); output.append("\n"); output.append(content.toUnicodeString().replaceAll("\r", "\r\n")); output.append("\n"); } } } } catch (Exception e) { Logger.getLogger(CommentExtractorApp.class.getName()).log(Level.SEVERE, null, e); } return new String(output); }
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 v a 2s . c om 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; } }