These examples were written in the context of Chapter 13 of the book "iText in Action - Second Edition".
/* in_action/chapterF/HelloWorldPdfX.java */ package part4.chapter13; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.CMYKColor; import com.itextpdf.text.pdf.ICC_Profile; import com.itextpdf.text.pdf.PdfAConformanceLevel; import com.itextpdf.text.pdf.PdfAWriter; import com.itextpdf.text.pdf.PdfWriter; public class PdfXPdfA { /** The resulting PDF file. */ public static final String RESULT1 = "results/part4/chapter13/x.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "results/part4/chapter13/a.pdf"; /** A font program that is used. */ public static final String FONT = "c:/windows/fonts/arial.ttf"; /** A color profile that is used. */ public static final String PROFILE = "resources/img/sRGB.profile"; /** * Creates a PDF document. * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdfX(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); writer.setPDFXConformance(PdfWriter.PDFX1A2001); // step 3 document.open(); // step 4 Font font = FontFactory.getFont( FONT, BaseFont.CP1252, BaseFont.EMBEDDED, Font.UNDEFINED, Font.UNDEFINED, new CMYKColor(255, 255, 0, 0)); document.add(new Paragraph("Hello World", font)); // step 5 document.close(); } /** * Creates a PDF document. * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdfA(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfAWriter writer = PdfAWriter.getInstance(document, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1B); writer.createXmpMetadata(); // step 3 document.open(); // step 4 Font font = FontFactory.getFont(FONT, BaseFont.CP1252, BaseFont.EMBEDDED); document.add(new Paragraph("Hello World", font)); ICC_Profile icc = ICC_Profile.getInstance(new FileInputStream(PROFILE)); writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); // step 5 document.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { PdfXPdfA example = new PdfXPdfA(); example.createPdfX(RESULT1); example.createPdfA(RESULT2); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import part1.chapter01.HelloWorld; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; public class AppendMode { /** The resulting PDF. */ public static final String RESULT = "results/part4/chapter13/appended.pdf"; /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), '\0', true); PdfContentByte cb = stamper.getUnderContent(1); cb.beginText(); cb.setFontAndSize(BaseFont.createFont(), 12); cb.showTextAligned(Element.ALIGN_LEFT, "Hello People!", 36, 770, 0); cb.endText(); stamper.close(); reader.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { new HelloWorld().createPdf(HelloWorld.RESULT); new AppendMode().manipulatePdf(HelloWorld.RESULT, RESULT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLException; import java.util.List; import part1.chapter02.MovieParagraphs1; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import com.lowagie.database.DatabaseConnection; import com.lowagie.database.HsqldbConnection; import com.lowagie.filmfestival.Movie; import com.lowagie.filmfestival.PojoFactory; public class PageLayoutExample extends MovieParagraphs1 { /** The resulting PDF file. */ public static final String RESULT1 = "results/part4/chapter13/page_layout_single.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "results/part4/chapter13/page_layout_column.pdf"; /** The resulting PDF file. */ public static final String RESULT3 = "results/part4/chapter13/page_layout_columns_l.pdf"; /** The resulting PDF file. */ public static final String RESULT4 = "results/part4/chapter13/page_layout_columns_r.pdf"; /** The resulting PDF file. */ public static final String RESULT5 = "results/part4/chapter13/page_layout_pages_l.pdf"; /** The resulting PDF file. */ public static final String RESULT6 = "results/part4/chapter13/page_layout_pages_r.pdf"; /** * Creates a PDF with information about the movies * @param filename the name of the PDF file that will be created. * @param pagelayout the value for the viewerpreferences * @throws DocumentException * @throws IOException * @throws SQLException */ public void createPdf(String filename, int viewerpreference) throws IOException, DocumentException, SQLException { // Create a database connection DatabaseConnection connection = new HsqldbConnection("filmfestival"); // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(viewerpreference); // step 3 document.open(); // step 4 List<Movie> movies = PojoFactory.getMovies(connection); for (Movie movie : movies) { Paragraph p = createMovieInformation(movie); p.setAlignment(Element.ALIGN_JUSTIFIED); p.setIndentationLeft(18); p.setFirstLineIndent(-18); document.add(p); } // step 5 document.close(); // Close the database connection connection.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, DocumentException, SQLException { PageLayoutExample example = new PageLayoutExample(); example.createPdf(RESULT1, PdfWriter.PageLayoutSinglePage); example.createPdf(RESULT2, PdfWriter.PageLayoutOneColumn); example.createPdf(RESULT3, PdfWriter.PageLayoutTwoColumnLeft); example.createPdf(RESULT4, PdfWriter.PageLayoutTwoColumnRight); example.createPdf(RESULT5, PdfWriter.PageLayoutTwoPageLeft); example.createPdf(RESULT6, PdfWriter.PageLayoutTwoPageRight); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.IOException; import java.sql.SQLException; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfWriter; public class ViewerPreferencesExample extends PageLayoutExample { /** The resulting PDF file. */ public static final String RESULT1 = "results/part4/chapter13/viewerpreferences1.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "results/part4/chapter13/viewerpreferences2.pdf"; /** The resulting PDF file. */ public static final String RESULT3 = "results/part4/chapter13/viewerpreferences3.pdf"; /** The resulting PDF file. */ public static final String RESULT4 = "results/part4/chapter13/viewerpreferences4.pdf"; /** The resulting PDF file. */ public static final String RESULT5 = "results/part4/chapter13/viewerpreferences5.pdf"; /** The resulting PDF file. */ public static final String RESULT6 = "results/part4/chapter13/viewerpreferences6.pdf"; /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, DocumentException, SQLException { ViewerPreferencesExample example = new ViewerPreferencesExample(); example.createPdf(RESULT1, PdfWriter.PageModeFullScreen); example.createPdf(RESULT2, PdfWriter.PageModeUseThumbs); example.createPdf(RESULT3, PdfWriter.PageLayoutTwoColumnRight | PdfWriter.PageModeUseThumbs); example.createPdf(RESULT4, PdfWriter.PageModeFullScreen | PdfWriter.NonFullScreenPageModeUseOutlines); example.createPdf(RESULT5, PdfWriter.FitWindow | PdfWriter.HideToolbar); example.createPdf(RESULT6, PdfWriter.HideWindowUI); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfBoolean; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfNumber; import com.itextpdf.text.pdf.PdfWriter; public class PrintPreferencesExample { /** The resulting PDF file. */ public static final String RESULT = "results/part4/chapter13/printpreferences.pdf"; /** * Creates a PDF with information about the movies * @param filename the name of the PDF file that will be created. * @param pagelayout the value for the viewerpreferences * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); writer.addViewerPreference(PdfName.NUMCOPIES, new PdfNumber(3)); writer.addViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfBoolean.PDFTRUE); // step 3 document.open(); // step 4 document.add(new Paragraph("Hello World")); // step 5 document.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { new PrintPreferencesExample().createPdf(RESULT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import part1.chapter03.MovieTemplates; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfRectangle; import com.itextpdf.text.pdf.PdfStamper; public class CropPages { /** The resulting PDF. */ public static final String RESULT = "results/part4/chapter13/timetable_cropped.pdf"; /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); int n = reader.getNumberOfPages(); PdfDictionary pageDict; PdfRectangle rect = new PdfRectangle(55, 76, 560, 816); for (int i = 1; i <= n; i++) { pageDict = reader.getPageN(i); pageDict.put(PdfName.CROPBOX, rect); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { new MovieTemplates().createPdf(MovieTemplates.RESULT); new CropPages().manipulatePdf(MovieTemplates.RESULT, RESULT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import part1.chapter03.MovieTemplates; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfNumber; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; public class RotatePages { /** The resulting PDF. */ public static final String RESULT = "results/part4/chapter13/timetable_rotated.pdf"; /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(MovieTemplates.RESULT); int n = reader.getNumberOfPages(); int rot; PdfDictionary pageDict; for (int i = 1; i <= n; i++) { rot = reader.getPageRotation(i); pageDict = reader.getPageN(i); pageDict.put(PdfName.ROTATE, new PdfNumber(rot + 90)); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); stamper.close(); reader.close(); } /** * Main method creating the PDF. * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { new MovieTemplates().createPdf(MovieTemplates.RESULT); new RotatePages().manipulatePdf(MovieTemplates.RESULT, RESULT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import part2.chapter07.LaunchAction; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfObject; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfString; public class RemoveLaunchActions { /** The resulting PDF. */ public static final String RESULT = "results/part4/chapter13/launch_removed.pdf"; /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws DocumentException, IOException { PdfReader reader = new PdfReader(src); PdfObject object; PdfDictionary action; for (int i = 1; i < reader.getXrefSize(); i++) { object = reader.getPdfObject(i); if (object instanceof PdfDictionary) { action = ((PdfDictionary)object).getAsDict(PdfName.A); if (action == null) continue; if (PdfName.LAUNCH.equals(action.getAsName(PdfName.S))) { action.remove(PdfName.F); action.remove(PdfName.WIN); action.put(PdfName.S, PdfName.JAVASCRIPT); action.put(PdfName.JS, new PdfString("app.alert('Launch Application Action removed by iText');\r")); } } } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * Main method creating the PDF. * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { new LaunchAction().createPdf(LaunchAction.RESULT); new RemoveLaunchActions().manipulatePdf(LaunchAction.RESULT, RESULT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfArray; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfPageLabels; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfString; import com.itextpdf.text.pdf.PdfWriter; import com.lowagie.database.DatabaseConnection; import com.lowagie.database.HsqldbConnection; public class PageLabelExample { /** The resulting PDF file. */ public static final String RESULT = "results/part4/chapter13/page_labels.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "results/part4/chapter13/page_labels_changed.pdf"; /** A text file containing page numbers and labels. */ public static final String LABELS = "results/part4/chapter13/page_labels.txt"; /** SQL statements */ public static final String[] SQL = { "SELECT country FROM film_country ORDER BY country", "SELECT name FROM film_director ORDER BY name", "SELECT title FROM film_movietitle ORDER BY title" }; /** SQL statements */ public static final String[] FIELD = { "country", "name", "title" }; /** * Creates a PDF document. * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException * @throws SQLException */ public void createPdf(String filename) throws IOException, DocumentException, SQLException{ DatabaseConnection connection = new HsqldbConnection("filmfestival"); // step 1 Document document = new Document(PageSize.A5); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 int[] start = new int[3]; for (int i = 0; i < 3; i++) { start[i] = writer.getPageNumber(); addParagraphs(document, connection, SQL[i], FIELD[i]); document.newPage(); } PdfPageLabels labels = new PdfPageLabels(); labels.addPageLabel(start[0], PdfPageLabels.UPPERCASE_LETTERS); labels.addPageLabel(start[1], PdfPageLabels.DECIMAL_ARABIC_NUMERALS); labels.addPageLabel(start[2], PdfPageLabels.DECIMAL_ARABIC_NUMERALS, "Movies-", start[2] - start[1] + 1); writer.setPageLabels(labels); // step 5 document.close(); connection.close(); } /** * Performs an SQL query and writes the results to a PDF using the Paragraph object. * @param document The document to which the paragraphs have to be added * @param connection The database connection that has to be used * @param sql The SQL statement * @param field The name of the field that has to be shown * @throws SQLException * @throws DocumentException * @throws IOException */ public void addParagraphs(Document document, DatabaseConnection connection, String sql, String field) throws SQLException, DocumentException, IOException { Statement stm = connection.createStatement(); ResultSet rs = stm.executeQuery(sql); while (rs.next()) { document.add(new Paragraph(new String(rs.getBytes(field), "UTF-8"))); } } /** * Reads the page labels from an existing PDF * @param src the path to an existing PDF * @param dest the path to the resulting text file * @throws IOException */ public void listPageLabels(String src, String dest) throws IOException { // no PDF, just a text file PrintStream out = new PrintStream(new FileOutputStream(dest)); PdfReader reader = new PdfReader(src); String[] labels = PdfPageLabels.getPageLabels(reader); for (int i = 0; i < labels.length; i++) { out.println(labels[i]); } out.flush(); out.close(); reader.close(); } /** * Manipulates the page labels at the lowest PDF level. * @param src The path to the source file * @param dest The path to the changed PDF * @throws IOException * @throws DocumentException */ public void manipulatePageLabel(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfDictionary root = reader.getCatalog(); PdfDictionary labels = root.getAsDict(PdfName.PAGELABELS); PdfArray nums = labels.getAsArray(PdfName.NUMS); int n; PdfDictionary pagelabel; for (int i = 0; i < nums.size(); i++) { n = nums.getAsNumber(i).intValue(); i++; if (n == 5) { pagelabel = nums.getAsDict(i); pagelabel.remove(PdfName.ST); pagelabel.put(PdfName.P, new PdfString("Film-")); } } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, DocumentException, SQLException { PageLabelExample labels = new PageLabelExample(); labels.createPdf(RESULT); labels.listPageLabels(RESULT, LABELS); labels.manipulatePageLabel(RESULT, RESULT2); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLException; import java.util.Set; import java.util.TreeSet; import part2.chapter07.LinkActions; import com.itextpdf.text.Chapter; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Section; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.pdf.PdfArray; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfIndirectReference; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; import com.lowagie.database.DatabaseConnection; import com.lowagie.database.HsqldbConnection; import com.lowagie.filmfestival.Movie; import com.lowagie.filmfestival.MovieComparator; import com.lowagie.filmfestival.PojoFactory; import com.lowagie.filmfestival.PojoToElementFactory; public class Bookmarks2NamedDestinations { /** The resulting PDF file. */ public static final String RESULT1 = "results/part4/chapter13/bookmarks.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "results/part4/chapter13/named_destinations.pdf"; /** The resulting PDF file. */ public static final String RESULT3 = "results/part4/chapter13/named_destinations.xml"; /** The different epochs. */ public static final String[] EPOCH = { "Forties", "Fifties", "Sixties", "Seventies", "Eighties", "Nineties", "Twenty-first Century" }; /** The fonts for the title. */ public static final Font[] FONT = new Font[4]; static { FONT[0] = new Font(FontFamily.HELVETICA, 24); FONT[1] = new Font(FontFamily.HELVETICA, 18); FONT[2] = new Font(FontFamily.HELVETICA, 14); FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD); } /** * Creates a PDF document. * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException * @throws DocumentException * @throws IOException * @throws SQLException */ public void createPdf(String filename) throws IOException, DocumentException, SQLException { DatabaseConnection connection = new HsqldbConnection("filmfestival"); // step 1 Document document = new Document(); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 Set<Movie> movies = new TreeSet<Movie>(new MovieComparator(MovieComparator.BY_YEAR)); movies.addAll(PojoFactory.getMovies(connection)); int epoch = -1; int currentYear = 0; Paragraph title = null; Chapter chapter = null; Section section = null; for (Movie movie : movies) { // add the chapter if we're in a new epoch if (epoch < (movie.getYear() - 1940) / 10) { epoch = (movie.getYear() - 1940) / 10; if (chapter != null) { document.add(chapter); } title = new Paragraph(EPOCH[epoch], FONT[0]); chapter = new Chapter(title, epoch + 1); chapter.setBookmarkTitle(EPOCH[epoch]); } // switch to a new year if (currentYear < movie.getYear()) { currentYear = movie.getYear(); title = new Paragraph( String.format("The year %d", movie.getYear()), FONT[1]); section = chapter.addSection(title); section.setBookmarkTitle(String.valueOf(movie.getYear())); section.setIndentation(30); section.setBookmarkOpen(false); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section.add(new Paragraph( String.format("Movies from the year %d:", movie.getYear()))); } title = new Paragraph(movie.getMovieTitle(), FONT[2]); section.add(title); section.add(new Paragraph("Duration: " + movie.getDuration(), FONT[3])); section.add(new Paragraph("Director(s):", FONT[3])); section.add(PojoToElementFactory.getDirectorList(movie)); section.add(new Paragraph("Countries:", FONT[3])); section.add(PojoToElementFactory.getCountryList(movie)); } document.add(chapter); // step 5 document.close(); connection.close(); } /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfDictionary root = reader.getCatalog(); PdfDictionary outlines = root.getAsDict(PdfName.OUTLINES); if (outlines == null) return; PdfArray dests = new PdfArray(); addKids(dests, outlines.getAsDict(PdfName.FIRST)); if (dests.size() == 0) return; PdfIndirectReference ref = reader.addPdfObject(dests); PdfDictionary nametree = new PdfDictionary(); nametree.put(PdfName.NAMES, ref); PdfDictionary names = new PdfDictionary(); names.put(PdfName.DESTS, nametree); root.put(PdfName.NAMES, names); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * Adds Outline dictionaries to an array of destinations. * @param dests * @param outline */ public static void addKids(PdfArray dests, PdfDictionary outline) { while (outline != null) { dests.add(outline.getAsString(PdfName.TITLE)); dests.add(outline.getAsArray(PdfName.DEST)); addKids(dests, outline.getAsDict(PdfName.FIRST)); outline = outline.getAsDict(PdfName.NEXT); } } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, DocumentException, SQLException { Bookmarks2NamedDestinations example = new Bookmarks2NamedDestinations(); example.createPdf(RESULT1); example.manipulatePdf(RESULT1, RESULT2); new LinkActions().createXml(RESULT2, RESULT3); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.PdfArray; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; public class FixBrokenForm { /** The original PDF file. */ public static final String ORIGINAL = "resources/pdfs/broken_form.pdf"; /** The resulting PDF file. */ public static final String FIXED = "results/part4/chapter13/fixed_form.pdf"; /** The original PDF file that couldn't be filled out. */ public static final String RESULT1 = "results/part4/chapter13/broken_form.pdf"; /** The fixed PDF file that was correctly filled out. */ public static final String RESULT2 = "results/part4/chapter13/filled_form.pdf"; /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfDictionary root = reader.getCatalog(); PdfDictionary form = root.getAsDict(PdfName.ACROFORM); PdfArray fields = form.getAsArray(PdfName.FIELDS); PdfDictionary page; PdfArray annots; for (int i = 1; i <= reader.getNumberOfPages(); i++) { page = reader.getPageN(i); annots = page.getAsArray(PdfName.ANNOTS); for (int j = 0; j < annots.size(); j++) { fields.add(annots.getAsIndirectObject(j)); } } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * @param src * @param dest * @throws IOException * @throws DocumentException */ public void fillData(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); AcroFields form = stamper.getAcroFields(); form.setField("title", "The Misfortunates"); form.setField("director", "Felix Van Groeningen"); form.setField("year", "2009"); form.setField("duration", "108"); stamper.close(); reader.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { FixBrokenForm example = new FixBrokenForm(); example.manipulatePdf(ORIGINAL, FIXED); example.fillData(ORIGINAL, RESULT1); example.fillData(FIXED, RESULT2); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Map; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.BaseField; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import part2.chapter08.Subscribe; public class InspectForm { /** A text file containing information about a form. */ public static final String RESULTTXT = "results/part4/chapter13/fieldflags.txt"; /** * Inspects a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void inspectPdf(String src, String dest) throws IOException, DocumentException { OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(dest)); PdfReader reader = new PdfReader(src); AcroFields form = reader.getAcroFields(); Map<String,AcroFields.Item> fields = form.getFields(); AcroFields.Item item; PdfDictionary dict; int flags; for (Map.Entry<String,AcroFields.Item> entry : fields.entrySet()) { out.write(entry.getKey()); item = entry.getValue(); dict = item.getMerged(0); flags = dict.getAsNumber(PdfName.FF).intValue(); if ((flags & BaseField.PASSWORD) > 0) out.write(" -> password"); if ((flags & BaseField.MULTILINE) > 0) out.write(" -> multiline"); out.write('\n'); } out.flush(); out.close(); reader.close(); } /** * Inspects a form. * @param args no arguments needed * @throws IOException * @throws DocumentException */ public static void main(String[] args) throws IOException, DocumentException { new Subscribe().createPdf(Subscribe.RESULT); new InspectForm().inspectPdf(Subscribe.RESULT, RESULTTXT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Rectangle; import com.itextpdf.text.Utilities; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.GrayColor; import com.itextpdf.text.pdf.PdfAction; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfFormField; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.PushbuttonField; import com.itextpdf.text.pdf.RadioCheckField; import com.itextpdf.text.pdf.TextField; public class AddJavaScriptToForm { /** The resulting PDF file. */ public static final String ORIGINAL = "results/part4/chapter13/form_without_js.pdf"; /** The resulting PDF file. */ public static final String RESULT = "results/part4/chapter13/form_with_js.pdf"; /** Path to the resources. */ public static final String RESOURCE = "resources/js/extra.js"; /** * Creates a PDF document. * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException * @throws SQLException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 BaseFont bf = BaseFont.createFont(); PdfContentByte directcontent = writer.getDirectContent(); directcontent.beginText(); directcontent.setFontAndSize(bf, 12); directcontent.showTextAligned(Element.ALIGN_LEFT, "Married?", 36, 770, 0); directcontent.showTextAligned(Element.ALIGN_LEFT, "YES", 58, 750, 0); directcontent.showTextAligned(Element.ALIGN_LEFT, "NO", 102, 750, 0); directcontent.showTextAligned(Element.ALIGN_LEFT, "Name partner?", 36, 730, 0); directcontent.endText(); // create a radio button field PdfFormField married = PdfFormField.createRadioButton(writer, true); married.setFieldName("married"); married.setValueAsName("Yes"); Rectangle rectYes = new Rectangle(40, 766, 56, 744); RadioCheckField yes = new RadioCheckField(writer, rectYes, null, "Yes"); yes.setChecked(true); married.addKid(yes.getRadioField()); Rectangle rectNo = new Rectangle(84, 766, 100, 744); RadioCheckField no = new RadioCheckField(writer, rectNo, null, "No"); no.setChecked(false); married.addKid(no.getRadioField()); writer.addAnnotation(married); // create a text field Rectangle rect = new Rectangle(40, 710, 200, 726); TextField partner = new TextField(writer, rect, "partner"); partner.setBorderColor(GrayColor.GRAYBLACK); partner.setBorderWidth(0.5f); writer.addAnnotation(partner.getTextField()); // step 5 document.close(); } /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { // Create a reader and a stamper PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); // Get the writer from the stamper PdfWriter writer = stamper.getWriter(); // Add JavaScript writer.addJavaScript(Utilities.readFileToString(RESOURCE)); // get the form fields AcroFields form = stamper.getAcroFields(); AcroFields.Item fd = form.getFieldItem("married"); // Get the PDF dictionary of the YES radio button and add an additional action PdfDictionary dictYes = (PdfDictionary) PdfReader.getPdfObject(fd.getWidgetRef(0)); PdfDictionary yesAction = dictYes.getAsDict(PdfName.AA); if (yesAction == null) yesAction = new PdfDictionary(); yesAction.put(new PdfName("Fo"), PdfAction.javaScript("setReadOnly(false);", stamper.getWriter())); dictYes.put(PdfName.AA, yesAction); // Get the PDF dictionary of the NO radio button and add an additional action PdfDictionary dictNo = (PdfDictionary) PdfReader.getPdfObject(fd.getWidgetRef(1)); PdfDictionary noAction = dictNo.getAsDict(PdfName.AA); if (noAction == null) noAction = new PdfDictionary(); noAction.put(new PdfName("Fo"), PdfAction.javaScript("setReadOnly(true);", stamper.getWriter())); dictNo.put(PdfName.AA, noAction); // Create a submit button and add it to the stamper PushbuttonField button = new PushbuttonField(writer, new Rectangle(40, 690, 200, 710), "submit"); button.setText("validate and submit"); button.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT); PdfFormField validateAndSubmit = button.getField(); validateAndSubmit.setAction(PdfAction.javaScript("validate();", stamper.getWriter())); stamper.addAnnotation(validateAndSubmit, 1); // close the stamper stamper.close(); reader.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, DocumentException { AddJavaScriptToForm example = new AddJavaScriptToForm(); example.createPdf(ORIGINAL); example.manipulatePdf(ORIGINAL, RESULT); } }
/* * This class is part of the book "iText in Action - 2nd Edition" * written by Bruno Lowagie (ISBN: 9781935182610) * For more info, go to: http://itextpdf.com/examples/ * This example only works with the AGPL version of iText. */ package part4.chapter13; import java.io.FileOutputStream; import java.io.IOException; import part2.chapter08.ChildFieldEvent; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.GrayColor; import com.itextpdf.text.pdf.PdfAction; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfFormField; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfString; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.PushbuttonField; import com.itextpdf.text.pdf.TextField; public class ReplaceURL { /** The resulting PDF file. */ public static final String RESULT1 = "results/part4/chapter13/submit1.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "results/part4/chapter13/submit2.pdf"; /** * Creates a PDF document. * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfFormField personal = PdfFormField.createEmpty(writer); personal.setFieldName("personal"); PdfPTable table = new PdfPTable(3); PdfPCell cell; table.addCell("Your name:"); cell = new PdfPCell(); cell.setColspan(2); TextField field = new TextField(writer, new Rectangle(0, 0), "name"); field.setFontSize(12); cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1)); table.addCell(cell); table.addCell("Login:"); cell = new PdfPCell(); field = new TextField(writer, new Rectangle(0, 0), "loginname"); field.setFontSize(12); cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1)); table.addCell(cell); cell = new PdfPCell(); field = new TextField(writer, new Rectangle(0, 0), "password"); field.setOptions(TextField.PASSWORD); field.setFontSize(12); cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1)); table.addCell(cell); table.addCell("Your motivation:"); cell = new PdfPCell(); cell.setColspan(2); cell.setFixedHeight(60); field = new TextField(writer, new Rectangle(0, 0), "reason"); field.setOptions(TextField.MULTILINE); field.setFontSize(12); cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1)); table.addCell(cell); document.add(table); writer.addAnnotation(personal); PushbuttonField button1 = new PushbuttonField( writer, new Rectangle(90, 660, 140, 690), "post"); button1.setText("POST"); button1.setBackgroundColor(new GrayColor(0.7f)); button1.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT); PdfFormField submit1 = button1.getField(); submit1.setAction(PdfAction.createSubmitForm("/book/request", null, PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES)); writer.addAnnotation(submit1); // step 5 document.close(); } /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); AcroFields form = reader.getAcroFields(); AcroFields.Item item = form.getFieldItem("post"); PdfDictionary field = item.getMerged(0); PdfDictionary action = field.getAsDict(PdfName.A); PdfDictionary f = action.getAsDict(PdfName.F); f.put(PdfName.F, new PdfString("http://itextpdf.com:8080/book/request")); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { ReplaceURL form = new ReplaceURL(); form.createPdf(RESULT1); form.manipulatePdf(RESULT1, RESULT2); } }
File name | Raw URL | Updated |
---|---|---|
PdfXPdfA.java | PdfXPdfA.java | 2015-10-10 3:19 pm |
AppendMode.java | AppendMode.java | 2015-10-10 3:19 pm |
PageLayoutExample.java | PageLayoutExample.java | 2015-10-10 3:19 pm |
ViewerPreferencesExample.java | ViewerPreferencesExample.java | 2015-10-10 3:19 pm |
PrintPreferencesExample.java | PrintPreferencesExample.java | 2015-10-10 3:19 pm |
CropPages.java | CropPages.java | 2015-10-10 3:19 pm |
RotatePages.java | RotatePages.java | 2015-10-10 3:19 pm |
RemoveLaunchActions.java | RemoveLaunchActions.java | 2015-10-10 3:19 pm |
PageLabelExample.java | PageLabelExample.java | 2015-10-10 3:19 pm |
Bookmarks2NamedDestinations.java | Bookmarks2NamedDestinations.java | 2015-10-10 3:19 pm |
FixBrokenForm.java | FixBrokenForm.java | 2015-10-10 3:19 pm |
InspectForm.java | InspectForm.java | 2015-10-10 3:19 pm |
AddJavaScriptToForm.java | AddJavaScriptToForm.java | 2015-10-10 3:19 pm |
ReplaceURL.java | ReplaceURL.java | 2015-10-10 3:19 pm |
File name | Raw URL | Updated |
---|---|---|
PdfXPdfA.cs | PdfXPdfA.cs | 2015-10-10 3:20 pm |
AppendMode.cs | AppendMode.cs | 2015-10-10 3:20 pm |
PageLayoutExample.cs | PageLayoutExample.cs | 2015-10-10 3:20 pm |
ViewerPreferencesExample.cs | ViewerPreferencesExample.cs | 2015-10-10 3:20 pm |
PrintPreferencesExample.cs | PrintPreferencesExample.cs | 2015-10-10 3:20 pm |
CropPages.cs | CropPages.cs | 2015-10-10 3:20 pm |
RotatePages.cs | RotatePages.cs | 2015-10-10 3:20 pm |
RemoveLaunchActions.cs | RemoveLaunchActions.cs | 2015-10-10 3:20 pm |
PageLabelExample.cs | PageLabelExample.cs | 2015-10-10 3:20 pm |
Bookmarks2NamedDestinations.cs | Bookmarks2NamedDestinations.cs | 2015-10-10 3:20 pm |
FixBrokenForm.cs | FixBrokenForm.cs | 2015-10-10 3:20 pm |
InspectForm.cs | InspectForm.cs | 2015-10-10 3:20 pm |
AddJavaScriptToForm.cs | AddJavaScriptToForm.cs | 2015-10-10 3:20 pm |
ReplaceURL.cs | ReplaceURL.cs | 2015-10-10 3:20 pm |