List of usage examples for com.itextpdf.text.pdf PdfWriter VERSION_1_6
char VERSION_1_6
To view the source code for com.itextpdf.text.pdf PdfWriter VERSION_1_6.
Click Source Link
From source file:avalonscrollmaker20.AnothakScribe.java
License:Open Source License
private void initializeDoc() { // Create a Document doc_scrolls = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f); // Get a DocWriter instance try {//from ww w . j a v a 2s . c o m doc_writer = PdfWriter.getInstance(doc_scrolls, new FileOutputStream(doc_name)); doc_writer.setPdfVersion(PdfWriter.VERSION_1_6); } catch (Exception ex) { System.err.println(ex + "\nProgram closing."); System.exit(3); } // Open the Document doc_scrolls.addTitle(doc_name.substring(0, doc_name.length() - 3)); doc_scrolls.addSubject("A collection of Avalon-legal Anothak Scrolls"); doc_scrolls.addAuthor("Michael Weigle"); doc_scrolls.addCreator("Avalon Scrollmaker 2.0, powered by iText"); doc_scrolls.open(); }
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;//w ww . j av a 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:net.sf.texprinter.generators.PDFGenerator.java
License:Open Source License
/** * Generates a PDF file from a Question object. * //from w w w . ja v a2s. c o m * @param question The question. * @param filename The filename. */ public static void generate(Question question, String filename) { // wait window ProgressMessage pm = new ProgressMessage("TeXPrinter is printing your PDF file."); // start wait window //pm.start(); // log message log.log(Level.INFO, "Starting PDF generation of {0}.", filename); // define a new PDF document Document document = null; // define a new PDF writer PdfWriter writer = null; // lets try try { // create a new PDF document document = new Document(); // define a new PDF Writer writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // set the PDF version writer.setPdfVersion(PdfWriter.VERSION_1_6); // open the document document.open(); // set the title font Font titleFont = new Font(FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK); // set the chunk for the question title Chunk questionTitle = new Chunk(question.getQuestion().getTitle(), titleFont); // create a paragraph from that chunk Paragraph paragraphQuestionTitle = new Paragraph(questionTitle); // log message log.log(Level.INFO, "Adding the question title."); // add the question title to the document document.add(paragraphQuestionTitle); // set the asker font Font askerFont = new Font(FontFamily.HELVETICA, 10, Font.ITALIC, BaseColor.DARK_GRAY); // set the chunk for the asker Chunk questionAsker = new Chunk("Asked by " + question.getQuestion().getUser().getName() + " (" + question.getQuestion().getUser().getReputation() + ") on " + question.getQuestion().getDate() + " (" + String.valueOf(question.getQuestion().getVotes()) + (question.getQuestion().getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // create a paragraph from that chunk Paragraph paragraphQuestionAsker = new Paragraph(questionAsker); // log message log.log(Level.INFO, "Adding both asker and reputation."); // add the asker to the document document.add(paragraphQuestionAsker); // create a line separator LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -5); // add the line to the document document.add(line); // add a new line document.add(Chunk.NEWLINE); // create a list of elements from the question objects List<Element> questionTextObjects = getPostText(question.getQuestion().getText()); // log message log.log(Level.INFO, "Adding the question text."); // for each element for (Element questionTextObject : questionTextObjects) { // add it to the document document.add(questionTextObject); } // add a new line document.add(Chunk.NEWLINE); // create a new font for the comments title Font commentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); // create a new chunk based on that font Chunk commentsTitle = new Chunk( "This question has " + question.getQuestion().getComments().size() + ((question.getQuestion().getComments().size() == 1) ? " comment:" : " comments:"), commentsTitleFont); // create a paragraph from that chunk Paragraph paragraphCommentsTitle = new Paragraph(commentsTitle); // if there are comments to this question if (!question.getQuestion().getComments().isEmpty()) { // log message log.log(Level.INFO, "Adding the question comments."); // add that paragraph to the document document.add(paragraphCommentsTitle); // add a new line document.add(Chunk.NEWLINE); // get all the comments List<Comment> questionComments = question.getQuestion().getComments(); // for each comment for (Comment questionComment : questionComments) { // get the elements of the comment text List<Element> questionCommentObjects = getPostText(questionComment.getText()); // for each element for (Element questionCommentObject : questionCommentObjects) { // add it to the document document.add(questionCommentObject); } // create a new paragraph about the comment author Paragraph paragraphCommentAuthor = new Paragraph(questionComment.getAuthor() + " on " + questionComment.getDate() + " (" + String.valueOf(questionComment.getVotes()) + (questionComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // set the alignment to the right paragraphCommentAuthor.setAlignment(Element.ALIGN_RIGHT); // add the paragraph to the document document.add(paragraphCommentAuthor); // add a new line document.add(Chunk.NEWLINE); } } // add a line separator document.add(line); // add two new lines document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); // get the list of answers List<Post> answersList = question.getAnswers(); // if there are no answers if (answersList.isEmpty()) { // log message log.log(Level.INFO, "This question has no answers."); // create a new chunk Chunk noAnswersTitle = new Chunk("Sorry, this question has no answers yet.", titleFont); // create a paragraph from that chunk Paragraph paragraphNoAnswersTitle = new Paragraph(noAnswersTitle); // add the paragraph to the document document.add(paragraphNoAnswersTitle); } else { // log message log.log(Level.INFO, "Adding answers."); // there are answers, so create a counter for answers int answerCount = 1; // for each answer for (Post answer : answersList) { // log message log.log(Level.INFO, "Adding answer {0}.", answerCount); // set the message text as empty String answerAccepted = ""; // if the answer is accepted if (answer.isAccepted()) { // add that to the message answerAccepted = " - Marked as accepted."; } // create a new chunk Chunk answerTitle = new Chunk("Answer #" + answerCount, titleFont); // create a paragraph from that chunk Paragraph paragraphAnswerTitle = new Paragraph(answerTitle); // add the paragraph to the document document.add(paragraphAnswerTitle); // increase the counter answerCount++; // create a new chunk Chunk questionAnswerer = new Chunk("Answered by " + answer.getUser().getName() + " (" + answer.getUser().getReputation() + ") on " + answer.getDate() + answerAccepted + " (" + String.valueOf(answer.getVotes()) + (answer.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // create a paragraph from that chunk Paragraph paragraphQuestionAnswerer = new Paragraph(questionAnswerer); // add that paragraph to the document document.add(paragraphQuestionAnswerer); // add a line separator document.add(line); // add a new line document.add(Chunk.NEWLINE); // create a list of elements from the answer text List<Element> answerTextObjects = getPostText(answer.getText()); // for each element for (Element answerTextObject : answerTextObjects) { // add it to the document document.add(answerTextObject); } // add a new line document.add(Chunk.NEWLINE); // create a new font style Font answerCommentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); // create a new chunk Chunk answerCommentsTitle = new Chunk( "This answer has " + answer.getComments().size() + ((answer.getComments().size() == 1) ? " comment:" : " comments:"), answerCommentsTitleFont); // create a paragraph from that chunk Paragraph paragraphAnswerCommentsTitle = new Paragraph(answerCommentsTitle); // if there are comments for that answer if (!answer.getComments().isEmpty()) { // log message log.log(Level.INFO, "Adding comments for answer {0}.", (answerCount - 1)); // add that paragraph to the document document.add(paragraphAnswerCommentsTitle); // add a new line document.add(Chunk.NEWLINE); // get all the comments List<Comment> answerComments = answer.getComments(); // for each comment for (Comment answerComment : answerComments) { // create a list of elements from the comment text List<Element> answerCommentObjects = getPostText(answerComment.getText()); // for each element for (Element answerCommentObject : answerCommentObjects) { // add it to the document document.add(answerCommentObject); } // create a new paragraph for the comment author Paragraph paragraphAnswerCommentAuthor = new Paragraph( answerComment.getAuthor() + " on " + answerComment.getDate() + " (" + String.valueOf(answerComment.getVotes()) + (answerComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // set the aligment to the right paragraphAnswerCommentAuthor.setAlignment(Element.ALIGN_RIGHT); // add the paragraph to the document document.add(paragraphAnswerCommentAuthor); // add a new line document.add(Chunk.NEWLINE); } } // add a line separator document.add(line); // add two new lines document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); } } // log message log.log(Level.INFO, "PDF generation complete, closing {0}.", filename); // close the document document.close(); // stop wait window pm.interrupt(); } catch (IOException ioexception) { // stop wait window pm.interrupt(); // log message log.log(Level.SEVERE, "An IO error occurred while trying to create the PDF file. MESSAGE: {0}", StringUtils.printStackTrace(ioexception)); // critical error, exit Dialogs.showExceptionWindow(); } catch (Exception exception) { // log message log.log(Level.SEVERE, "A generic error occurred while trying to create the PDF file. MESSAGE: {0}", StringUtils.printStackTrace(exception)); // log message log.log(Level.INFO, "I will try to remove the remaining PDF file."); try { // log message log.log(Level.INFO, "Closing both document and writer."); // close the document document.close(); // close the writer writer.close(); } catch (Exception ex) { // log message log.log(Level.WARNING, "I could not close either document or writer. MESSAGE: {0}", StringUtils.printStackTrace(ex)); } try { // reference problematic file File target = new File(filename); // log message log.log(Level.INFO, "Opening problematic file {0}.", filename); // check if file exists if (target.exists()) { // log message log.log(Level.INFO, "File exists, trying to delete it."); // trying to remove it if (target.delete()) { // log message log.log(Level.INFO, "File {0} was successfully removed.", filename); } else { // log message log.log(Level.SEVERE, "File {0} could not be removed.", filename); } } } catch (SecurityException se) { // log message log.log(Level.SEVERE, "A security exception was raised. MESSAGE: {0}", StringUtils.printStackTrace(se)); } // stop wait window pm.interrupt(); // critical error, exit Dialogs.showExceptionWindow(); } }
From source file:pdfcreator.PDFCreator.java
License:Open Source License
@SuppressWarnings("static-access") protected void createPdf(String filename, String[] images) throws Exception { Document doc = new Document(); PdfWriter writer;/*w w w . j a v a 2 s .c o m*/ if (pdfxConformance.equals("PDFA1A")) { writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1A); } else if (pdfxConformance.equals("PDFA1B")) { writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1B); } else if (pdfxConformance.equals("PDFA2A")) { writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2A); } else if (pdfxConformance.equals("PDFA2B")) { writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2B); } else if (pdfxConformance.equals("PDFA3A")) { writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3A); } else if (pdfxConformance.equals("PDFA3B")) { writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3B); } else { writer = PdfWriter.getInstance(doc, new FileOutputStream(filename)); } if (pdfVersion.equals("1.4")) { writer.setPdfVersion(PdfWriter.VERSION_1_4); } else if (pdfVersion.equals("1.5")) { writer.setPdfVersion(PdfWriter.VERSION_1_5); } else if (pdfVersion.equals("1.6")) { writer.setPdfVersion(PdfWriter.VERSION_1_6); } else if (pdfVersion.equals("1.7")) { writer.setPdfVersion(PdfWriter.VERSION_1_7); } else { writer.setPdfVersion(PdfWriter.VERSION_1_4); } verbose(filename + ": open"); doc.addCreationDate(); doc.addCreator(creator); if (title != null) { doc.addTitle(title); } for (int i = 0; i < images.length; i++) { verbose(" +" + images[i]); Image img = Image.getInstance(images[i]); doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); doc.setMargins(0, 0, 0, 0); if (doc.isOpen()) { doc.newPage(); } else { doc.open(); } doc.add(img); doc.newPage(); } ICC_Profile icc = getImageColorProfile(images[0]); if (icc == null) { System.err.println("warning: no color profile available in " + images[0] + " using " + profileName); icc = getDefaultColorProfile(); } writer.setOutputIntents("Custom", "", null, null, icc); writer.createXmpMetadata(); doc.close(); verbose(filename + ": close"); }