// --------------------------------------------------------------------------- public override void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { HtmlMovies2 movies = new HtmlMovies2(); // create a StyleSheet StyleSheet styles = new StyleSheet(); styles.LoadTagStyle("ul", "indent", "10"); styles.LoadTagStyle("li", "leading", "14"); styles.LoadStyle("country", "i", ""); styles.LoadStyle("country", "color", "#008080"); styles.LoadStyle("director", "b", ""); styles.LoadStyle("director", "color", "midnightblue"); movies.SetStyles(styles); // create extra properties Dictionary <String, Object> map = new Dictionary <String, Object>(); map.Add(HTMLWorker.FONT_PROVIDER, new MyFontFactory()); map.Add(HTMLWorker.IMG_PROVIDER, new MyImageFactory()); movies.SetProviders(map); // creates HTML and PDF (reusing a method from the super class) byte[] pdf = movies.CreateHtmlAndPdf(stream); zip.AddEntry(HTML, movies.Html.ToString()); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, movies.CreatePdf()); // add the images so the static html file works foreach (Movie movie in PojoFactory.GetMovies()) { zip.AddFile( Path.Combine( Utility.ResourcePosters, string.Format("{0}.jpg", movie.Imdb) ), "" ); } zip.Save(stream); } }
/** * Fills out a data sheet, flattens it, and adds it to a combined PDF. * @param copy the PdfCopy instance (can also be PdfSmartCopy) */ public void AddDataSheets(PdfCopy copy) { IEnumerable <Movie> movies = PojoFactory.GetMovies(); // Loop over all the movies and fill out the data sheet foreach (Movie movie in movies) { PdfReader reader = new PdfReader(DATASHEET_PATH); using (var ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { stamper.AcroFields.GenerateAppearances = true; Fill(stamper.AcroFields, movie); stamper.FormFlattening = true; } reader.Close(); reader = new PdfReader(ms.ToArray()); copy.AddPage(copy.GetImportedPage(reader, 1)); copy.FreeReader(reader); } reader.Close(); } }
// --------------------------------------------------------------------------- /** * Creates the PDF. * @return the bytes of a PDF file. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); document.Add(new Paragraph( "This is a list of Kubrick movies available in DVD stores." )); IEnumerable <Movie> movies = PojoFactory.GetMovies(1) .Concat(PojoFactory.GetMovies(4)) ; List list = new List(); string RESOURCE = Utility.ResourcePosters; foreach (Movie movie in movies) { PdfAnnotation annot = PdfAnnotation.CreateFileAttachment( writer, null, movie.GetMovieTitle(false), null, Path.Combine(RESOURCE, movie.Imdb + ".jpg"), string.Format("{0}.jpg", movie.Imdb) ); ListItem item = new ListItem(movie.GetMovieTitle(false)); item.Add("\u00a0\u00a0"); Chunk chunk = new Chunk("\u00a0\u00a0\u00a0\u00a0"); chunk.SetAnnotation(annot); item.Add(chunk); list.Add(item); } document.Add(list); } return(ms.ToArray()); } }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { string SQL = @"SELECT country, id FROM film_country ORDER BY country "; using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document(PageSize.A4, 36, 36, 72, 36)) { // step 2 PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { document.Add(new Paragraph( r["country"].ToString(), FilmFonts.BOLD )); document.Add(Chunk.NEWLINE); foreach (Movie movie in PojoFactory.GetMovies(r["id"].ToString(), true)) { document.Add(new Paragraph( movie.MovieTitle, FilmFonts.BOLD )); if (!string.IsNullOrEmpty(movie.OriginalTitle)) { document.Add( new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC )); } document.Add(new Paragraph( String.Format( "Year: {0}; run length: {1} minutes", movie.Year, movie.Duration ), FilmFonts.NORMAL )); document.Add(PojoToElementFactory.GetDirectorList(movie)); } document.NewPage(); } } } } } return(ms.ToArray()); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfCollection collection = new PdfCollection(PdfCollection.HIDDEN); PdfCollectionSchema schema = _collectionSchema(); collection.Schema = schema; PdfCollectionSort sort = new PdfCollectionSort(KEYS); collection.Sort = sort; writer.Collection = collection; PdfCollectionItem collectionitem = new PdfCollectionItem(schema); PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, IMG_KUBRICK, "kubrick.jpg", null ); fs.AddDescription("Stanley Kubrick", false); collectionitem.AddItem(TYPE_FIELD, "JPEG"); fs.AddCollectionItem(collectionitem); writer.AddFileAttachment(fs); Image img = Image.GetInstance(IMG_BOX); document.Add(img); List list = new List(List.UNORDERED, 20); PdfDestination dest = new PdfDestination(PdfDestination.FIT); dest.AddFirst(new PdfNumber(1)); PdfTargetDictionary intermediate; PdfTargetDictionary target; Chunk chunk; ListItem item; PdfAction action = null; IEnumerable <Movie> box = PojoFactory.GetMovies(1) .Concat(PojoFactory.GetMovies(4)) ; StringBuilder sb = new StringBuilder(); foreach (Movie movie in box) { if (movie.Year > 1960) { sb.AppendLine(String.Format( "{0};{1};{2}", movie.MovieTitle, movie.Year, movie.Duration )); item = new ListItem(movie.MovieTitle); if (!"0278736".Equals(movie.Imdb)) { target = new PdfTargetDictionary(true); target.EmbeddedFileName = movie.Title; intermediate = new PdfTargetDictionary(true); intermediate.FileAttachmentPage = 1; intermediate.FileAttachmentIndex = 1; intermediate.AdditionalPath = target; action = PdfAction.GotoEmbedded(null, intermediate, dest, true); chunk = new Chunk(" (see info)"); chunk.SetAction(action); item.Add(chunk); } list.Add(item); } } document.Add(list); fs = PdfFileSpecification.FileEmbedded( writer, null, "kubrick.txt", Encoding.UTF8.GetBytes(sb.ToString()) ); fs.AddDescription("Kubrick box: the movies", false); collectionitem.AddItem(TYPE_FIELD, "TXT"); fs.AddCollectionItem(collectionitem); writer.AddFileAttachment(fs); PdfPTable table = new PdfPTable(1); table.SpacingAfter = 10; PdfPCell cell = new PdfPCell(new Phrase("All movies by Kubrick")); cell.Border = PdfPCell.NO_BORDER; fs = PdfFileSpecification.FileEmbedded( writer, null, KubrickMovies.FILENAME, Utility.PdfBytes(new KubrickMovies()) //new KubrickMovies().createPdf() ); collectionitem.AddItem(TYPE_FIELD, "PDF"); fs.AddCollectionItem(collectionitem); target = new PdfTargetDictionary(true); target.FileAttachmentPagename = "movies"; target.FileAttachmentName = "The movies of Stanley Kubrick"; cell.CellEvent = new PdfActionEvent( writer, PdfAction.GotoEmbedded(null, target, dest, true) ); cell.CellEvent = new FileAttachmentEvent( writer, fs, "The movies of Stanley Kubrick" ); cell.CellEvent = new LocalDestinationEvent(writer, "movies"); table.AddCell(cell); writer.AddFileAttachment(fs); cell = new PdfPCell(new Phrase("Kubrick DVDs")); cell.Border = PdfPCell.NO_BORDER; fs = PdfFileSpecification.FileEmbedded( writer, null, KubrickDvds.RESULT, new KubrickDvds().CreatePdf() ); collectionitem.AddItem(TYPE_FIELD, "PDF"); fs.AddCollectionItem(collectionitem); cell.CellEvent = new FileAttachmentEvent(writer, fs, "Kubrick DVDs"); table.AddCell(cell); writer.AddFileAttachment(fs); cell = new PdfPCell(new Phrase("Kubrick documentary")); cell.Border = PdfPCell.NO_BORDER; fs = PdfFileSpecification.FileEmbedded( writer, null, KubrickDocumentary.RESULT, new KubrickDocumentary().CreatePdf() ); collectionitem.AddItem(TYPE_FIELD, "PDF"); fs.AddCollectionItem(collectionitem); cell.CellEvent = new FileAttachmentEvent( writer, fs, "Kubrick Documentary" ); table.AddCell(cell); writer.AddFileAttachment(fs); document.NewPage(); document.Add(table); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Director director; using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { // create a paragraph for the director director = PojoFactory.GetDirector(r); Paragraph p = new Paragraph( PojoToElementFactory.GetDirectorPhrase(director)); // add a dotted line separator p.Add(new Chunk(new DottedLineSeparator())); // adds the number of movies of this director p.Add(string.Format("movies: {0}", Convert.ToInt32(r["c"]))); document.Add(p); // Creates a list List list = new List(List.ORDERED); list.IndentationLeft = 36; list.IndentationRight = 36; // Gets the movies of the current director var director_id = Convert.ToInt32(r["id"]); ListItem movieitem; // LINQ allows us to on sort any movie object property inline; // let's sort by Movie.Year, Movie.Title var by_year = from m in PojoFactory.GetMovies(director_id) orderby m.Year, m.Title select m; // loops over the movies foreach (Movie movie in by_year) { // creates a list item with a movie title movieitem = new ListItem(movie.MovieTitle); // adds a vertical position mark as a separator movieitem.Add(new Chunk(new VerticalPositionMark())); var yr = movie.Year; // adds the year the movie was produced movieitem.Add(new Chunk(yr.ToString())); // add an arrow to the right if the movie dates from 2000 or later if (yr > 1999) { movieitem.Add(PositionedArrow.RIGHT); } // add the list item to the list list.Add(movieitem); } // add the list to the document document.Add(list); } } } } } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 var SQL = @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c FROM film_country c, film_movie_country mc WHERE c.id = mc.country_id GROUP BY mc.country_id, country ORDER BY c DESC"; // Create a new list List list = new List(List.ORDERED); list.Autoindent = false; list.SymbolIndent = 36; // loop over the countries using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { // create a list item for the country ListItem item = new ListItem( string.Format("{0}: {1} movies", r["country"].ToString(), r["c"].ToString() ) ); item.ListSymbol = new Chunk(r["country_id"].ToString()); // Create a list for the movies produced in the current country List movielist = new List(List.ORDERED, List.ALPHABETICAL); movielist.Alignindent = false; foreach (Movie movie in PojoFactory.GetMovies(r["country_id"].ToString()) ) { ListItem movieitem = new ListItem(movie.MovieTitle); List directorlist = new List(List.ORDERED); directorlist.PreSymbol = "Director "; directorlist.PostSymbol = ": "; foreach (Director director in movie.Directors) { directorlist.Add(String.Format("{0}, {1}", director.Name, director.GivenName )); } movieitem.Add(directorlist); movielist.Add(movieitem); } item.Add(movielist); list.Add(item); } document.Add(list); } } } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Director director; // creating separators LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2); Paragraph stars = new Paragraph(20); stars.Add(new Chunk(StarSeparator.LINE)); stars.SpacingAfter = 30; using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { // get the director object and use it in a Paragraph director = PojoFactory.GetDirector(r); Paragraph p = new Paragraph( PojoToElementFactory.GetDirectorPhrase(director)); // if there are more than 2 movies for this director // an arrow is added to the left var count = Convert.ToInt32(r["c"]); if (count > 2) { p.Add(PositionedArrow.LEFT); } p.Add(line); // add the paragraph with the arrow to the document document.Add(p); // Get the movies of the director var director_id = Convert.ToInt32(r["id"]); // LINQ allows us to sort on any movie object property inline; // let's sort by Movie.Year, Movie.Title var by_year = from m in PojoFactory.GetMovies(director_id) orderby m.Year, m.Title select m; foreach (Movie movie in by_year) { p = new Paragraph(movie.MovieTitle); p.Add(": "); p.Add(new Chunk(movie.Year.ToString())); if (movie.Year > 1999) { p.Add(PositionedArrow.RIGHT); } document.Add(p); } // add a star separator after the director info is added document.Add(stars); } } } } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document(PageSize.A4, 36, 36, 54, 54)) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); HeaderFooter tevent = new HeaderFooter(); writer.SetBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.PageEvent = tevent; // step 3 document.Open(); // step 4 int epoch = -1; int currentYear = 0; Paragraph title = null; iTextSharp.text.Chapter chapter = null; Section section = null; Section subsection = null; // add the chapters, sort by year foreach (Movie movie in PojoFactory.GetMovies(true)) { int year = movie.Year; if (epoch < (year - 1940) / 10) { epoch = (year - 1940) / 10; if (chapter != null) { document.Add(chapter); } title = new Paragraph(EPOCH[epoch], FONT[0]); chapter = new iTextSharp.text.Chapter(title, epoch + 1); } if (currentYear < year) { currentYear = year; title = new Paragraph( String.Format("The year {0}", year), FONT[1] ); section = chapter.AddSection(title); section.BookmarkTitle = year.ToString(); section.Indentation = 30; section.BookmarkOpen = false; section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT; section.Add(new Paragraph( String.Format("Movies from the year {0}:", year)) ); } title = new Paragraph(movie.MovieTitle, FONT[2]); subsection = section.AddSection(title); subsection.IndentationLeft = 20; subsection.NumberDepth = 1; subsection.Add(new Paragraph( "Duration: " + movie.Duration.ToString(), FONT[3] )); subsection.Add(new Paragraph("Director(s):", FONT[3])); subsection.Add(PojoToElementFactory.GetDirectorList(movie)); subsection.Add(new Paragraph("Countries:", FONT[3])); subsection.Add(PojoToElementFactory.GetCountryList(movie)); } document.Add(chapter); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.SetTagged(); writer.UserProperties = true; // step 3 document.Open(); // step 4 PdfStructureTreeRoot tree = writer.StructureTreeRoot; PdfStructureElement top = new PdfStructureElement( tree, new PdfName("Directors") ); Dictionary <int, PdfStructureElement> directors = new Dictionary <int, PdfStructureElement>(); int id; Director director; PdfStructureElement e; DbProviderFactory dbp = AdoDB.Provider; using (var c = dbp.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SELECTDIRECTORS; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { id = Convert.ToInt32(r["id"]); director = PojoFactory.GetDirector(r); e = new PdfStructureElement(top, new PdfName("director" + id)); PdfDictionary userproperties = new PdfDictionary(); userproperties.Put(PdfName.O, PdfName.USERPROPERTIES); PdfArray properties = new PdfArray(); PdfDictionary property1 = new PdfDictionary(); property1.Put(PdfName.N, new PdfString("Name")); property1.Put(PdfName.V, new PdfString(director.Name)); properties.Add(property1); PdfDictionary property2 = new PdfDictionary(); property2.Put(PdfName.N, new PdfString("Given name")); property2.Put(PdfName.V, new PdfString(director.GivenName)); properties.Add(property2); PdfDictionary property3 = new PdfDictionary(); property3.Put(PdfName.N, new PdfString("Posters")); property3.Put(PdfName.V, new PdfNumber(Convert.ToInt32(r["c"]))); properties.Add(property3); userproperties.Put(PdfName.P, properties); e.Put(PdfName.A, userproperties); directors.Add(id, e); } } } } Dictionary <Movie, int> map = new Dictionary <Movie, int>(); for (int i = 1; i < 8; i++) { foreach (Movie movie in PojoFactory.GetMovies(i)) { map.Add(movie, i); } } PdfContentByte canvas = writer.DirectContent; Image img; float x = 11.5f; float y = 769.7f; string RESOURCE = Utility.ResourcePosters; foreach (var entry in map.Keys) { img = Image.GetInstance(Path.Combine(RESOURCE, entry.Imdb + ".jpg")); img.ScaleToFit(1000, 60); img.SetAbsolutePosition(x + (45 - img.ScaledWidth) / 2, y); canvas.BeginMarkedContentSequence(directors[map[entry]]); canvas.AddImage(img); canvas.EndMarkedContentSequence(); x += 48; if (x > 578) { x = 11.5f; y -= 84.2f; } } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // IMPORTANT: set linear page mode! writer.SetLinearPageMode(); ChapterSectionTOC tevent = new ChapterSectionTOC(new MovieHistory1()); writer.PageEvent = tevent; // step 3 document.Open(); // step 4 int epoch = -1; int currentYear = 0; Paragraph title = null; iTextSharp.text.Chapter chapter = null; Section section = null; Section subsection = null; // add the chapters, sort by year foreach (Movie movie in PojoFactory.GetMovies(true)) { int year = movie.Year; if (epoch < (year - 1940) / 10) { epoch = (year - 1940) / 10; if (chapter != null) { document.Add(chapter); } title = new Paragraph(EPOCH[epoch], FONT[0]); chapter = new iTextSharp.text.Chapter(title, epoch + 1); } if (currentYear < year) { currentYear = year; title = new Paragraph( String.Format("The year {0}", year), FONT[1] ); section = chapter.AddSection(title); section.BookmarkTitle = year.ToString(); section.Indentation = 30; section.BookmarkOpen = false; section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT; section.Add(new Paragraph( String.Format("Movies from the year {0}:", year)) ); } title = new Paragraph(movie.MovieTitle, FONT[2]); subsection = section.AddSection(title); subsection.IndentationLeft = 20; subsection.NumberDepth = 1; subsection.Add(new Paragraph( "Duration: " + movie.Duration.ToString(), FONT[3] )); subsection.Add(new Paragraph("Director(s):", FONT[3])); subsection.Add(PojoToElementFactory.GetDirectorList(movie)); subsection.Add(new Paragraph("Countries:", FONT[3])); subsection.Add(PojoToElementFactory.GetCountryList(movie)); } document.Add(chapter); // add the TOC starting on the next page document.NewPage(); int toc = writer.PageNumber; foreach (Paragraph p in tevent.titles) { document.Add(p); } // always go to a new page before reordering pages. document.NewPage(); // get the total number of pages that needs to be reordered int total = writer.ReorderPages(null); // change the order int[] order = new int[total]; for (int i = 0; i < total; i++) { order[i] = i + toc; if (order[i] > total) { order[i] -= total; } } // apply the new order writer.ReorderPages(order); } }
// =========================================================================== public override void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 IEnumerable <Movie> movies = PojoFactory.GetMovies(); foreach (Movie movie in movies) { // Create a paragraph with the title Paragraph title = new Paragraph( PojoToElementFactory.GetMovieTitlePhrase(movie) ); title.Alignment = Element.ALIGN_LEFT; document.Add(title); // Add the original title next to it using a dirty hack if (!string.IsNullOrEmpty(movie.OriginalTitle)) { Paragraph dummy = new Paragraph("\u00a0", FilmFonts.NORMAL); dummy.Leading = -18; document.Add(dummy); Paragraph originalTitle = new Paragraph( PojoToElementFactory.GetOriginalTitlePhrase(movie) ); originalTitle.Alignment = Element.ALIGN_RIGHT; document.Add(originalTitle); } // Info about the director float indent = 20; // Loop over the directors foreach (Director pojo in movie.Directors) { Paragraph director = new Paragraph( PojoToElementFactory.GetDirectorPhrase(pojo) ); director.IndentationLeft = indent; document.Add(director); indent += 20; } // Info about the country indent = 20; // Loop over the countries foreach (Country pojo in movie.Countries) { Paragraph country = new Paragraph( PojoToElementFactory.GetCountryPhrase(pojo) ); country.Alignment = Element.ALIGN_RIGHT; country.IndentationRight = indent; document.Add(country); indent += 20; } // Extra info about the movie Paragraph info = CreateYearAndDuration(movie); info.Alignment = Element.ALIGN_CENTER; info.SpacingAfter = 36; document.Add(info); } } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 document.Add(new Paragraph("Movies:")); IEnumerable <Movie> movies = PojoFactory.GetMovies(); List list; PdfPCell cell; string RESOURCE = Utility.ResourcePosters; foreach (Movie movie in movies) { // a table with two columns PdfPTable table = new PdfPTable(new float[] { 1, 7 }); table.WidthPercentage = 100; table.SpacingBefore = 5; // a cell with an image cell = new PdfPCell( Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg")), true ); cell.Border = PdfPCell.NO_BORDER; table.AddCell(cell); cell = new PdfPCell(); // a cell with paragraphs and lists Paragraph p = new Paragraph(movie.Title, FilmFonts.BOLD); p.Alignment = Element.ALIGN_CENTER; p.SpacingBefore = 5; p.SpacingAfter = 5; cell.AddElement(p); cell.Border = PdfPCell.NO_BORDER; if (!string.IsNullOrEmpty(movie.OriginalTitle)) { p = new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC); p.Alignment = Element.ALIGN_RIGHT; cell.AddElement(p); } list = PojoToElementFactory.GetDirectorList(movie); list.IndentationLeft = 30; cell.AddElement(list); p = new Paragraph( string.Format("Year: {0}", movie.Year), FilmFonts.NORMAL ); p.IndentationLeft = 15; p.Leading = 24; cell.AddElement(p); p = new Paragraph( string.Format("Run length: {0}", movie.Duration), FilmFonts.NORMAL ); p.Leading = 14; p.IndentationLeft = 30; cell.AddElement(p); list = PojoToElementFactory.GetCountryList(movie); list.IndentationLeft = 40; cell.AddElement(list); table.AddCell(cell); // every movie corresponds with one table document.Add(table); // but the result looks like one big table } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { MovieAds movieAds = new MovieAds(); byte[] pdf = movieAds.CreateTemplate(); zip.AddEntry(TEMPLATE, pdf); using (MemoryStream msDoc = new MemoryStream()) { using (Document document = new Document()) { using (PdfSmartCopy copy = new PdfSmartCopy(document, msDoc)) { document.Open(); PdfReader reader; PdfStamper stamper = null; AcroFields form = null; int count = 0; MemoryStream ms = null; using (ms) { foreach (Movie movie in PojoFactory.GetMovies()) { if (count == 0) { ms = new MemoryStream(); reader = new PdfReader(RESOURCE); stamper = new PdfStamper(reader, ms); stamper.FormFlattening = true; form = stamper.AcroFields; } count++; PdfReader ad = new PdfReader( movieAds.FillTemplate(pdf, movie) ); PdfImportedPage page = stamper.GetImportedPage(ad, 1); PushbuttonField bt = form.GetNewPushbuttonFromField( "movie_" + count ); bt.Layout = PushbuttonField.LAYOUT_ICON_ONLY; bt.ProportionalIcon = true; bt.Template = page; form.ReplacePushbuttonField("movie_" + count, bt.Field); if (count == 16) { stamper.Close(); reader = new PdfReader(ms.ToArray()); copy.AddPage(copy.GetImportedPage(reader, 1)); count = 0; } } if (count > 0) { stamper.Close(); reader = new PdfReader(ms.ToArray()); copy.AddPage(copy.GetImportedPage(reader, 1)); } } } } zip.AddEntry(RESULT, msDoc.ToArray()); } zip.AddFile(RESOURCE, ""); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { string SQL = "SELECT country, id FROM film_country ORDER BY country"; using (ZipFile zip = new ZipFile()) { using (var ms = new MemoryStream()) { // FIRST PASS, CREATE THE PDF WITHOUT HEADER // step 1 using (Document document = new Document(PageSize.A4, 36, 36, 54, 36)) { // step 2 PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { document.Add(new Paragraph( r["country"].ToString(), FilmFonts.BOLD )); document.Add(Chunk.NEWLINE); string id = r["id"].ToString(); foreach (Movie movie in PojoFactory.GetMovies(id, true)) { document.Add(new Paragraph( movie.MovieTitle, FilmFonts.BOLD )); if (!string.IsNullOrEmpty(movie.OriginalTitle)) { document.Add(new Paragraph( movie.OriginalTitle, FilmFonts.ITALIC )); } document.Add(new Paragraph(string.Format( "Year: {0}; run length: {0} minutes", movie.Year, movie.Duration ), FilmFonts.NORMAL )); document.Add(PojoToElementFactory.GetDirectorList(movie)); } document.NewPage(); } } } } } byte[] firstPass = ms.ToArray(); zip.AddEntry("first-pass.pdf", firstPass); // SECOND PASS, ADD THE HEADER // Create a reader PdfReader reader = new PdfReader(firstPass); using (MemoryStream ms2 = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms2)) { // Loop over the pages and add a header to each page int n = reader.NumberOfPages; for (int i = 1; i <= n; i++) { GetHeaderTable(i, n).WriteSelectedRows( 0, -1, 34, 803, stamper.GetOverContent(i) ); } } zip.AddEntry(RESULT, ms2.ToArray()); } } zip.Save(stream); } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document(PageSize.A4)) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.CompressionLevel = 0; // step 3 document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; // Create the XObject PdfTemplate celluloid = canvas.CreateTemplate(595, 84.2f); celluloid.Rectangle(8, 8, 579, 68); for (float f = 8.25f; f < 581; f += 6.5f) { celluloid.RoundRectangle(f, 8.5f, 6, 3, 1.5f); celluloid.RoundRectangle(f, 72.5f, 6, 3, 1.5f); } celluloid.SetGrayFill(0.1f); celluloid.EoFill(); // Write the XObject to the OutputStream writer.ReleaseTemplate(celluloid); // Add the XObject 10 times for (int i = 0; i < 10; i++) { canvas.AddTemplate(celluloid, 0, i * 84.2f); } // Go to the next page document.NewPage(); // Add the XObject 10 times for (int i = 0; i < 10; i++) { canvas.AddTemplate(celluloid, 0, i * 84.2f); } // Get the movies from the database IEnumerable <Movie> movies = PojoFactory.GetMovies(); Image img; float x = 11.5f; float y = 769.7f; string RESOURCE = Utility.ResourcePosters; // Loop over the movies and add images foreach (Movie movie in movies) { img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg")); img.ScaleToFit(1000, 60); img.SetAbsolutePosition(x + (45 - img.ScaledWidth) / 2, y); canvas.AddImage(img); x += 48; if (x > 578) { x = 11.5f; y -= 84.2f; } } // Go to the next page document.NewPage(); // Add the template using a different CTM canvas.AddTemplate(celluloid, 0.8f, 0, 0.35f, 0.65f, 0, 600); // Wrap the XObject in an Image object Image tmpImage = Image.GetInstance(celluloid); tmpImage.SetAbsolutePosition(0, 480); document.Add(tmpImage); // Perform transformations on the image tmpImage.RotationDegrees = 30; tmpImage.ScalePercent(80); tmpImage.SetAbsolutePosition(30, 500); document.Add(tmpImage); // More transformations tmpImage.Rotation = (float)Math.PI / 2; tmpImage.SetAbsolutePosition(200, 300); document.Add(tmpImage); } }
/** * Creates a PDF with a table * @param writer the writer to our report file * @param filename the PDF that will be created * @throws IOException * @throws DocumentException * @throws SQLException */ private void CreatePdfWithPdfPTable(StreamWriter writer, Stream doc) { // Create a connection to the database //DatabaseConnection connection = new HsqldbConnection("filmfestival"); // step 1 Document document = new Document(); // step 2 PdfWriter.GetInstance(document, doc); // step 3 document.Open(); // step 4 // Create a table with 2 columns PdfPTable table = new PdfPTable(new float[] { 1, 7 }); // Mark the table as not complete if (test) { table.Complete = false; } table.WidthPercentage = 100; IEnumerable <Movie> movies = PojoFactory.GetMovies(); List list; PdfPCell cell; int count = 0; // add information about a movie foreach (Movie movie in movies) { table.SpacingBefore = 5; // add a movie poster cell = new PdfPCell(Image.GetInstance(String.Format(RESOURCE, movie.Imdb)), true); cell.Border = PdfPCell.NO_BORDER; table.AddCell(cell); // add movie information cell = new PdfPCell(); Paragraph p = new Paragraph(movie.Title, FilmFonts.BOLD); p.Alignment = Element.ALIGN_CENTER; p.SpacingBefore = 5; p.SpacingAfter = 5; cell.AddElement(p); cell.Border = PdfPCell.NO_BORDER; if (movie.OriginalTitle != null) { p = new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC); p.Alignment = Element.ALIGN_RIGHT; cell.AddElement(p); } list = PojoToElementFactory.GetDirectorList(movie); list.IndentationLeft = 30; cell.AddElement(list); p = new Paragraph(String.Format("Year: %d", movie.Year), FilmFonts.NORMAL); p.IndentationLeft = 15; p.Leading = 24; cell.AddElement(p); p = new Paragraph(String.Format("Run length: %d", movie.Duration), FilmFonts.NORMAL); p.Leading = 14; p.IndentationLeft = 30; cell.AddElement(p); list = PojoToElementFactory.GetCountryList(movie); list.IndentationLeft = 40; cell.AddElement(list); table.AddCell(cell); // insert a checkpoint every 10 movies if (count++ % 10 == 0) { // add the incomplete table to the document if (test) { document.Add(table); } Checkpoint(writer); } } // Mark the table as complete if (test) { table.Complete = true; } // add the table to the document document.Add(table); // insert a last checkpoint Checkpoint(writer); // step 5 document.Close(); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 var SQL = @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c FROM film_country c, film_movie_country mc WHERE c.id = mc.country_id GROUP BY mc.country_id, country ORDER BY c DESC"; // Create a list for the countries List list = new List(List.ORDERED); list.First = 9; // loop over the countries using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { // create a list item for the country ListItem item = new ListItem( string.Format("{0}: {1} movies", r["country"].ToString(), r["c"].ToString() ) ); // Create a list for the movies List movielist = new List(); movielist.ListSymbol = new Chunk("Movie: ", FilmFonts.BOLD); foreach (Movie movie in PojoFactory.GetMovies(r["country_id"].ToString()) ) { ListItem movieitem = new ListItem(movie.MovieTitle); // Create a list for the directors List directorlist = new ZapfDingbatsList(42); foreach (Director director in movie.Directors) { directorlist.Add(String.Format("{0}, {1}", director.Name, director.GivenName )); } movieitem.Add(directorlist); movielist.Add(movieitem); } item.Add(movielist); list.Add(item); } document.Add(list); } } } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Director director; // creates line separators Chunk CONNECT = new Chunk( new LineSeparator(0.5f, 95, BaseColor.BLUE, Element.ALIGN_CENTER, 3.5f) ); LineSeparator UNDERLINE = new LineSeparator( 1, 100, null, Element.ALIGN_CENTER, -2 ); // creates tabs Chunk tab1 = new Chunk(new VerticalPositionMark(), 200, true); Chunk tab2 = new Chunk(new VerticalPositionMark(), 350, true); Chunk tab3 = new Chunk(new DottedLineSeparator(), 450, true); using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { // loops over the directors while (r.Read()) { // creates a paragraph with the director name director = PojoFactory.GetDirector(r); Paragraph p = new Paragraph( PojoToElementFactory.GetDirectorPhrase(director)); // adds a separator p.Add(CONNECT); // adds more info about the director p.Add(string.Format("movies: {0}", Convert.ToInt32(r["c"]))); // adds a separator p.Add(UNDERLINE); // adds the paragraph to the document document.Add(p); // gets all the movies of the current director var director_id = Convert.ToInt32(r["id"]); // LINQ allows us to sort on any movie object property inline; // let's sort by Movie.Year, Movie.Title var by_year = from m in PojoFactory.GetMovies(director_id) orderby m.Year, m.Title select m; // loops over the movies foreach (Movie movie in by_year) { // create a Paragraph with the movie title p = new Paragraph(movie.MovieTitle); // insert a tab p.Add(new Chunk(tab1)); // add the original title var mt = movie.OriginalTitle; if (mt != null) { p.Add(new Chunk(mt)); } // insert a tab p.Add(new Chunk(tab2)); // add the run length of the movie p.Add(new Chunk(string.Format("{0} minutes", movie.Duration))); // insert a tab p.Add(new Chunk(tab3)); // add the production year of the movie p.Add(new Chunk( string.Format("{0}", movie.Year.ToString()) )); // add the paragraph to the document document.Add(p); } document.Add(Chunk.NEWLINE); } } } } } }
// --------------------------------------------------------------------------- /** * Creates a PDF with information about the movies * @param filename the name of the PDF file that will be created. */ public byte[] CreatePdf(int compression) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); switch (compression) { case -1: Document.Compress = false; break; case 0: writer.CompressionLevel = 0; break; case 2: writer.CompressionLevel = 9; break; case 3: writer.SetFullCompression(); break; } // step 3 document.Open(); // step 4 // Create database connection and statement var SQL = @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c FROM film_country c, film_movie_country mc WHERE c.id = mc.country_id GROUP BY mc.country_id, country ORDER BY c DESC"; // Create a new list List list = new List(List.ORDERED); DbProviderFactory dbp = AdoDB.Provider; using (var c = dbp.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { // create a list item for the country ListItem item = new ListItem( String.Format("{0}: {1} movies", r["country"], r["c"]), FilmFonts.BOLDITALIC ); // create a movie list for each country List movielist = new List(List.ORDERED, List.ALPHABETICAL); movielist.Lowercase = List.LOWERCASE; foreach (Movie movie in PojoFactory.GetMovies(r["country_id"].ToString())) { ListItem movieitem = new ListItem(movie.MovieTitle); List directorlist = new List(List.UNORDERED); foreach (Director director in movie.Directors) { directorlist.Add(String.Format( "{0}, {1}", director.Name, director.GivenName )); } movieitem.Add(directorlist); movielist.Add(movieitem); } item.Add(movielist); list.Add(item); } } } } document.Add(list); } Document.Compress = true; return(ms.ToArray()); } }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 int epoch = -1; int currentYear = 0; Paragraph title = null; iTextSharp.text.Chapter chapter = null; Section section = null; bool sortByYear = true; foreach (Movie movie in PojoFactory.GetMovies(sortByYear)) { // add the chapter if we're in a new epoch if (epoch < (movie.Year - 1940) / 10) { epoch = (movie.Year - 1940) / 10; if (chapter != null) { document.Add(chapter); } title = new Paragraph(EPOCH[epoch], FONT[0]); chapter = new iTextSharp.text.Chapter(title, epoch + 1); chapter.BookmarkTitle = EPOCH[epoch]; } // switch to a new year if (currentYear < movie.Year) { currentYear = movie.Year; title = new Paragraph( String.Format("The year {0}", movie.Year), FONT[1] ); section = chapter.AddSection(title); section.BookmarkTitle = movie.Year.ToString(); section.Indentation = 30; section.BookmarkOpen = false; section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT; section.Add(new Paragraph( String.Format("Movies from the year {0}:", movie.Year) )); } title = new Paragraph(movie.MovieTitle, FONT[2]); section.Add(title); section.Add(new Paragraph( "Duration: " + movie.Duration.ToString(), 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); } return(ms.ToArray()); } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document( new Rectangle(240, 240), 10, 10, 10, 10 )) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 // create a long Stringbuffer with movie titles StringBuilder sb = new StringBuilder(); IEnumerable <Movie> movies = PojoFactory.GetMovies(1); foreach (Movie movie in movies) { // replace spaces with non-breaking spaces sb.Append(movie.MovieTitle.Replace(' ', '\u00a0')); // use pipe as separator sb.Append('|'); } // Create a first chunk Chunk chunk1 = new Chunk(sb.ToString()); // wrap the chunk in a paragraph and add it to the document Paragraph paragraph = new Paragraph("A:\u00a0"); paragraph.Add(chunk1); paragraph.Alignment = Element.ALIGN_JUSTIFIED; document.Add(paragraph); document.Add(Chunk.NEWLINE); // define the pipe character as split character chunk1.SetSplitCharacter(new PipeSplitCharacter()); // wrap the chunk in a second paragraph and add it paragraph = new Paragraph("B:\u00a0"); paragraph.Add(chunk1); paragraph.Alignment = Element.ALIGN_JUSTIFIED; document.Add(paragraph); document.Add(Chunk.NEWLINE); // create a new StringBuffer with movie titles sb = new StringBuilder(); foreach (Movie movie in movies) { sb.Append(movie.MovieTitle); sb.Append('|'); } // Create a second chunk Chunk chunk2 = new Chunk(sb.ToString()); // wrap the chunk in a paragraph and add it to the document paragraph = new Paragraph("C:\u00a0"); paragraph.Add(chunk2); paragraph.Alignment = Element.ALIGN_JUSTIFIED; document.Add(paragraph); document.NewPage(); // define hyphenation for the chunk chunk2.SetHyphenation(new HyphenationAuto("en", "US", 2, 2)); // wrap the second chunk in a second paragraph and add it paragraph = new Paragraph("D:\u00a0"); paragraph.Add(chunk2); paragraph.Alignment = Element.ALIGN_JUSTIFIED; document.Add(paragraph); // go to a new page document.NewPage(); // define a new space/char ratio writer.SpaceCharRatio = PdfWriter.NO_SPACE_CHAR_RATIO; // wrap the second chunk in a third paragraph and add it paragraph = new Paragraph("E:\u00a0"); paragraph.Add(chunk2); paragraph.Alignment = Element.ALIGN_JUSTIFIED; document.Add(paragraph); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 int epoch = -1; int currentYear = 0; Paragraph title = null; iTextSharp.text.Chapter chapter = null; Section section = null; Section subsection = null; IEnumerable <Movie> movies = PojoFactory.GetMovies(true); // loop over the movies foreach (Movie movie in movies) { int yr = movie.Year; // add the chapter if we're in a new epoch if (epoch < (yr - 1940) / 10) { epoch = (yr - 1940) / 10; if (chapter != null) { document.Add(chapter); } title = new Paragraph(EPOCH[epoch], FONT[0]); chapter = new iTextSharp.text.Chapter(title, epoch + 1); } // switch to a new year if (currentYear < yr) { currentYear = yr; title = new Paragraph( string.Format("The year {0}", yr), FONT[1] ); section = chapter.AddSection(title); section.BookmarkTitle = yr.ToString(); section.Indentation = 30; section.BookmarkOpen = false; section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT; section.Add(new Paragraph( string.Format("Movies from the year {0}:", yr) )); } title = new Paragraph(movie.Title, FONT[2]); subsection = section.AddSection(title); subsection.IndentationLeft = 20; subsection.NumberDepth = 1; subsection.Add(new Paragraph("Duration: " + movie.Duration.ToString(), FONT[3])); subsection.Add(new Paragraph("Director(s):", FONT[3])); subsection.Add(PojoToElementFactory.GetDirectorList(movie)); subsection.Add(new Paragraph("Countries:", FONT[3])); subsection.Add(PojoToElementFactory.GetCountryList(movie)); } document.Add(chapter); } }