public void Archive(IEnumerable<FileInfo> files, string epubPath) { Document doc = new Document(); int chapterNumber = 1; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(epubPath, FileMode.Create)); doc.Open(); foreach (var file in files) { try { using (StreamReader sr = new StreamReader(file.FullName)) { string contents = sr.ReadToEnd(); /* string title = GetTitle(contents); // For redirect case. title = title == "" ? Path.GetFileNameWithoutExtension(file.Name) : title; * */ string title = GetTitleFromFilePath(file.Name); Chapter chapter1 = new Chapter(new Paragraph(title, _font), 1 /* chapterNumber */); /* var lists = HTMLWorker.ParseToList(new StringReader(contents), new StyleSheet()); lists.All((e) => chapter1.Add(e)); * */ chapter1.Add(new Paragraph(contents, _font)); try { doc.Add(chapter1); } catch (IndexOutOfRangeException) { //used unknown font. // just skip. continue; } } chapterNumber++; } catch (FileNotFoundException) { // in some Greeth filename, StreamReader return file not found exception. // Just ignore it. } } try { doc.Close(); } catch (IOException) { // if nothing add, close return IOException. // this is FileNotFoundException case only and just ignore it. } }
private static void SetAnchor(ISPage iSPage, Chapter chapter, Dictionary<string, int> pageMap) { Anchor anchorTarget = new Anchor(iSPage.RoomId); anchorTarget.Name = iSPage.RoomId; Paragraph targetParagraph = new Paragraph(); targetParagraph.Add(anchorTarget); chapter.Add(targetParagraph); }
// --------------------------------------------------------------------------- /** * 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; 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 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()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 int epoch = -1; int currentYear = 0; Paragraph title = null; 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 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); } }
public void AddChapter(Chapter chapter) { IT.Chapter tmp = new IT.Chapter(chapter.ChapterNumber); tmp.Title = new IT.Paragraph( chapter.Title ); //TODO : Add formatting foreach (var section in chapter.SubElements) { if (section is MultiColumnSection) { }else SectionFormatter.AddFormattedSection( (Section) section, tmp); } document.Add(tmp); }
public override void AddChapter(LnChapter lnChapter) { if (lnChapter.title == null) { lnChapter.title = string.Format(Globale.DEFAULT_CHAPTER_TITLE, lnChapter.chapNumber.ToString().PadLeft(3, '0')); } PdfChapter pdfChapter = new PdfChapter(lnChapter.title, lnChapter.chapNumber); foreach (string paragraph in lnChapter.paragraphs.ParseHtmlNodeToStringList()) { pdfChapter.Add( new PdfParagraph(paragraph) { Alignment = Element.ALIGN_JUSTIFIED, SpacingBefore = 15 }); } pdfChapters.Add(pdfChapter); }
//private static int chapterCount = 1; public static Chapter HtmlToPdfString(ISPage iSPage, int chapterNum, Dictionary<string, int> pageMap) { String htmlInput = iSPage.Contents; Chapter chapter = new Chapter(chapterNum.ToString(), 1); Font currentFont = FontFactory.GetFont(FontFactory.HELVETICA); SetAnchor(iSPage, chapter, pageMap); WriteContents(htmlInput, chapter); if (String.IsNullOrWhiteSpace(iSPage.EndText)) { WriteChoices(iSPage, pageMap, chapter); } else { WriteEnd(iSPage, chapter); } return chapter; }
// 函数描述:插一级标题 public static Chapter InsertChapterParagraph(string text, int chapterNumber) { var font = BaseFontAndSize("宋体", 12, Font.BOLD); text += "\n" + "---------------------------------------------------------------------------------------"; var paragraph = new Paragraph(text, font) { FirstLineIndent = 20, IndentationLeft = 0, SpacingBefore = 0, SpacingAfter = 0, Alignment = Element.ALIGN_LEFT }; //paragraph.SetLeading(1.5f, 1.5f); var chapter = new Chapter(paragraph, chapterNumber) { TriggerNewPage = false }; return chapter; }
public static void ExportComputerSpecification(Chapter chapter, Font font, ComputerConfiguration computerInfo) { Section sectionPC = chapter.AddSection(new Paragraph("Computer specification.", font)); sectionPC.Add(new Chunk("\n")); Section osSection = sectionPC.AddSection(new Paragraph("Operating System.", font)); string bits = computerInfo.OperatingSystem.Is64bit ? " 64bit" : "32bit"; osSection.Add(new Paragraph(String.Format("\t \t {0} {1}", computerInfo.OperatingSystem.Name, bits))); sectionPC.Add(new Chunk("\n")); Section processor = sectionPC.AddSection(new Paragraph("Processors.", font)); foreach (var pr in computerInfo.Processors) { processor.Add(new Paragraph(String.Format("\t \t Name: {0}", pr.Name))); processor.Add(new Paragraph(String.Format("\t \t Threads: {0}", pr.Threads))); processor.Add(new Paragraph(String.Format("\t \t Max clock speed: {0} MHz", pr.MaxClockSpeed))); } sectionPC.Add(new Chunk("\n")); Section memory = sectionPC.AddSection(new Paragraph("Memory modules.", font)); PdfPTable table = new PdfPTable(3); table.AddCell(CreateHeaderPdfPCell("Type")); table.AddCell(CreateHeaderPdfPCell("Capacity (GB)")); table.AddCell(CreateHeaderPdfPCell("Speed (MHz)")); foreach (var mem in computerInfo.MemoryModules) { table.AddCell(new PdfPCell(new Phrase(mem.MemoryType.ToString()))); table.AddCell(new PdfPCell(new Phrase(mem.Capacity.ToString())) { HorizontalAlignment = Element.ALIGN_RIGHT }); table.AddCell(new PdfPCell(new Phrase(mem.Speed.ToString())) { HorizontalAlignment = Element.ALIGN_RIGHT }); } memory.Add(new Chunk("\n")); memory.Add(table); sectionPC.Add(new Chunk("\n")); Section storage = sectionPC.AddSection(new Paragraph("Storages.", font)); table = new PdfPTable(3); table.AddCell(CreateHeaderPdfPCell("Model")); table.AddCell(CreateHeaderPdfPCell("Size (GB)")); table.AddCell(CreateHeaderPdfPCell("Partitions")); foreach (var stor in computerInfo.StorageDevices) { table.AddCell(new PdfPCell(new Phrase(stor.Model))); table.AddCell(new PdfPCell(new Phrase(stor.Size.ToString())) { HorizontalAlignment = Element.ALIGN_RIGHT }); table.AddCell(new PdfPCell(new Phrase(string.Join(",", stor.DriveLetters.Select(x => x.Replace(":", "")))))); } storage.Add(new Chunk("\n")); storage.Add(table); }
public static void Export(string file, Dictionary<TestMethod, StepFrame> frames, int flowCount, long recordCount, float randomness, ComputerConfiguration computerInfo, ReportType type) { var doc = new Document(PageSize.A4); if (File.Exists(file)) File.Delete(file); var fileStream = new FileStream(file, FileMode.OpenOrCreate); PdfWriter.GetInstance(doc, fileStream); doc.Open(); // Add header page. PdfPTable firstPageTable = new PdfPTable(1); firstPageTable.WidthPercentage = 100; PdfPCell title = new PdfPCell(); title.VerticalAlignment = Element.ALIGN_MIDDLE; title.HorizontalAlignment = Element.ALIGN_CENTER; title.MinimumHeight = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin); title.AddElement(Image.GetInstance((System.Drawing.Image)DatabaseBenchmark.Properties.Resources.logo_01, Color.WHITE)); firstPageTable.AddCell(title); doc.Add(firstPageTable); int chapterCount = 1; Font chapterFont = new Font(Font.TIMES_ROMAN, 16f, Font.TIMES_ROMAN, new Color(System.Drawing.Color.CornflowerBlue)); Chapter benchamrkConfiguration = new Chapter(new Paragraph("Benchmark parameters.", chapterFont), chapterCount++); benchamrkConfiguration.Add(new Chunk("\n")); ExportTestSettings(benchamrkConfiguration, chapterFont, flowCount, recordCount, randomness); ExportComputerSpecification(benchamrkConfiguration, chapterFont, computerInfo); doc.Add(benchamrkConfiguration); foreach (var fr in frames) { StepFrame frame = fr.Value; List<BarChart> barCharts; if (type == ReportType.Summary) barCharts = frame.GetSummaryBarCharts(); else barCharts = frame.GetAllBarCharts(); string chapterTitle = fr.Key == TestMethod.SecondaryRead ? "Secondary read" : fr.Key.ToString(); Chapter chapter = new Chapter(new Paragraph(chapterTitle, chapterFont), chapterCount++); chapter.Add(new Chunk("\n")); for (int i = 0; i < barCharts.Count; i++) { Image image = Image.GetInstance(barCharts[i].ConvertToByteArray()); image.Alignment = Element.ALIGN_CENTER; if (type == ReportType.Summary) image.ScaleToFit(doc.PageSize.Width - 20, 271); else image.ScalePercent(100); chapter.Add(image); } if (type == ReportType.Detailed) { PdfPTable table = new PdfPTable(1); table.WidthPercentage = 100; AddCellToTable(table, "Average Speed:", frame.lineChartAverageSpeed.ConvertToByteArray); AddCellToTable(table, "Moment Speed:", frame.lineChartMomentSpeed.ConvertToByteArray); AddCellToTable(table, "Average Memory:", frame.lineChartMomentMemory.ConvertToByteArray); //AddCellToTable(table, "Average CPU:", frame.lineChartAverageCPU.ConvertToByteArray); //AddCellToTable(table, "Average I/O:", frame.lineChartAverageIO.ConvertToByteArray); chapter.Add(table); } doc.Add(chapter); } doc.Close(); foreach (var item in frames) item.Value.ResetColumnStyle(); }
private static void WriteEnd(ISPage iSPage, Chapter chapter) { chapter.Add(new iTextSharp.text.Phrase(iSPage.EndText, FontFactory.GetFont(FontFactory.HELVETICA_BOLD))); }
// --------------------------------------------------------------------------- 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); // 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); } }
// --------------------------------------------------------------------------- /** * 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()); } }
/** * Constructs a RtfChapter for a given Chapter * * @param doc The RtfDocument this RtfChapter belongs to * @param chapter The Chapter this RtfChapter is based on */ public RtfChapter(RtfDocument doc, Chapter chapter) : base(doc, chapter) { }
private static void WriteContents(String htmlInput, Chapter chapter) { Font currentFont = FontFactory.GetFont(FontFactory.HELVETICA); string output = htmlInput; int position = 0; while (position < output.Length) { int nextLT = output.Substring(position).IndexOf('<') + position; if (nextLT < 0) { break; } if (position != nextLT) { chapter.Add(new iTextSharp.text.Chunk(output.Substring(position, nextLT - position), currentFont)); } int nextGT = output.Substring(position).IndexOf('>') + position; string tag = output.Substring(nextLT, nextGT - nextLT); position = nextGT + 1; if (tag.StartsWith("<img")) //insert image { if (tag.StartsWith("<img src=\"")) { int startQuote = tag.IndexOf("\"") + 1; int endQuote = tag.Substring(startQuote).IndexOf("\"") + startQuote; string imgPath = tag.Substring(startQuote, endQuote - startQuote); chapter.Add(Image.GetInstance(imgPath)); } } else if (tag.StartsWith("<p>")) //insert paragraph { chapter.Add(new iTextSharp.text.Chunk("\t", currentFont)); } else if (tag.StartsWith("<br>")) //insert line break { chapter.Add(new iTextSharp.text.Phrase("\r\n", currentFont)); } else if (tag.StartsWith("<b>")) //insert bold { if (currentFont.IsItalic()) { currentFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLDOBLIQUE); } else { currentFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD); } } else if (tag.StartsWith("<i>")) //insert italics { if (currentFont.IsBold()) { currentFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLDOBLIQUE); } else { currentFont = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE); } } else if (tag.StartsWith("</b>")) //insert bold { if (currentFont.IsItalic()) { currentFont = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE); } else { currentFont = FontFactory.GetFont(FontFactory.HELVETICA); } } else if (tag.StartsWith("</i>")) //insert italics { if (currentFont.IsBold()) { currentFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD); } else { currentFont = FontFactory.GetFont(FontFactory.HELVETICA); } } } }
//public void PDModel2Html(PDModel m) //{ // Export(m, ExportTyep.HTML); //} private void Export(IList<PDTable> tableList,string title, ExportTyep exportType) { Document doc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20); DocWriter w; switch (exportType) { case ExportTyep.PDF: w = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write)); break; case ExportTyep.RTF: w = RtfWriter2.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write)); break; //case ExportTyep.HTML: // w = HtmlWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write)); //break; default: break; } doc.Open(); doc.NewPage(); //IList<PDTable> tableList = m.AllTableList; //Chapter cpt = new Chapter(m.Name, 1); Chapter cpt = new Chapter(title, 1); Section sec; //doc.AddTitle(m.Name); doc.AddTitle(title); doc.AddAuthor("Kalman"); doc.AddCreationDate(); doc.AddCreator("Kalman"); doc.AddSubject("PDM数据库文档"); foreach (PDTable table in tableList) { sec = cpt.AddSection(new Paragraph(string.Format("{0}[{1}]", table.Name, table.Code), font)); if (string.IsNullOrEmpty(table.Comment) == false) { Chunk chunk = new Chunk(table.Comment, font); sec.Add(chunk); } t = new Table(9, table.ColumnList.Count); //t.Border = 15; //t.BorderColor = Color.BLACK; //t.BorderWidth = 1.0f; t.AutoFillEmptyCells = true; t.CellsFitPage = true; t.TableFitsPage = true; t.Cellpadding = 3; //if (exportType == ExportTyep.PDF) t.Cellspacing = 2; t.DefaultVerticalAlignment = Element.ALIGN_MIDDLE; t.SetWidths(new int[] { 200, 200, 150, 50, 50, 50, 50, 50, 300 }); t.AddCell(BuildHeaderCell("名称")); t.AddCell(BuildHeaderCell("代码")); t.AddCell(BuildHeaderCell("数据类型")); t.AddCell(BuildHeaderCell("长度")); t.AddCell(BuildHeaderCell("精度")); t.AddCell(BuildHeaderCell("主键")); t.AddCell(BuildHeaderCell("外键")); t.AddCell(BuildHeaderCell("可空")); t.AddCell(BuildHeaderCell("注释")); foreach (PDColumn column in table.ColumnList) { t.AddCell(BuildCell(column.Name)); t.AddCell(BuildCell(column.Code)); t.AddCell(BuildCell(column.DataType)); t.AddCell(BuildCell(column.Length == 0 ? "" : column.Length.ToString())); t.AddCell(BuildCell(column.Precision == 0 ? "" : column.Precision.ToString())); t.AddCell(BuildCell(column.IsPK ? " √" : "")); t.AddCell(BuildCell(column.IsFK ? " √" : "")); t.AddCell(BuildCell(column.Mandatory ? "" : " √")); t.AddCell(BuildCell(column.Comment)); } sec.Add(t); } doc.Add(cpt); doc.Close(); }
private List<SOTable> Export(DbSchema schema, SODatabase db, List<SOTable> tableList, ExportTyep exportType) { if (schema == null) throw new ArgumentException("参数schema不能为空", "schema"); if (db == null) throw new ArgumentException("参数dbName不能为空", "dbName"); Document doc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20); DocWriter w; switch (exportType) { case ExportTyep.PDF: w = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write)); break; case ExportTyep.RTF: w = RtfWriter2.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write)); break; //case ExportTyep.HTML: // w = HtmlWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write)); //break; default: break; } doc.Open(); doc.NewPage(); if (tableList == null) tableList = schema.GetTableList(db); Chapter cpt = new Chapter(db.Name, 1); Section sec; doc.AddTitle(db.Name); doc.AddAuthor("Kalman"); doc.AddCreationDate(); doc.AddCreator("Kalman"); doc.AddSubject("数据库文档"); foreach (SOTable table in tableList) { sec = cpt.AddSection(new Paragraph(table.Name, font)); if (string.IsNullOrEmpty(table.Comment) == false) { Chunk chunk = new Chunk(table.Comment, font); sec.Add(chunk); } List<SOColumn> columnList = schema.GetTableColumnList(table); t = new Table(7, columnList.Count); t.AutoFillEmptyCells = true; t.CellsFitPage = true; t.TableFitsPage = true; t.Cellpadding = 3; //if (exportType == ExportTyep.PDF) t.Cellspacing = 2; t.DefaultVerticalAlignment = Element.ALIGN_MIDDLE; t.SetWidths(new int[] { 200, 150, 50, 50, 50, 100, 300 }); t.AddCell(BuildHeaderCell("名称")); t.AddCell(BuildHeaderCell("数据类型")); t.AddCell(BuildHeaderCell("主键")); t.AddCell(BuildHeaderCell("标志")); t.AddCell(BuildHeaderCell("可空")); t.AddCell(BuildHeaderCell("默认值")); t.AddCell(BuildHeaderCell("注释")); foreach (SOColumn column in columnList) { t.AddCell(BuildCell(column.Name)); t.AddCell(BuildCell(GetDbColumnType(column))); t.AddCell(BuildCell(column.PrimaryKey ? " √" : "")); t.AddCell(BuildCell(column.Identify ? " √" : "")); t.AddCell(BuildCell(column.Nullable ? " √" : "")); t.AddCell(BuildCell(column.DefaultValue == null ? "" : column.DefaultValue.ToString())); t.AddCell(BuildCell(column.Comment)); } sec.Add(t); } doc.Add(cpt); doc.Close(); return tableList; }
public static void Genera(string sourcePath,string content) { sourcePath = HttpContext.Current.Server.MapPath(sourcePath); //定义一个Document,并设置页面大小为A4,竖向 iTextSharp.text.Document doc = new Document(PageSize.A4); try { //写实例 PdfWriter.GetInstance(doc, new FileStream(sourcePath, FileMode.Create)); //打开document doc.Open(); //载入字体 BaseFont baseFont = BaseFont.CreateFont( "C:\\WINDOWS\\FONTS\\SIMHEI.TTF", //黑体 BaseFont.IDENTITY_H, //横向字体 BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9); //写入一个段落, Paragraph doc.Add(new Paragraph("第一段:" + content, font)); doc.Add(new Paragraph("这是第二段 !", font)); #region 图片 //以下代码用来添加图片,此时图片是做为背景加入到pdf文件当中的: Stream inputImageStream = new FileStream(HttpContext.Current.Server.MapPath("~/images/logo.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream); image.SetAbsolutePosition(0, 0); image.Alignment = iTextSharp.text.Image.UNDERLYING; //这里可以设定图片是做为背景还是做为元素添加到文件中 doc.Add(image); #endregion #region 其他元素 doc.Add(new Paragraph("Hello World")); //另起一行。有几种办法建立一个段落,如: Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.\n", FontFactory.GetFont(FontFactory.HELVETICA, 12))); Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12))); Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); //所有有些对象将被添加到段落中: p1.Add("you can add string here\n\t"); p1.Add(new Chunk("you can add chunks \n")); p1.Add(new Phrase("or you can add phrases.\n")); doc.Add(p1); doc.Add(p2); doc.Add(p3); //创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块: Chunk chunk = new Chunk("创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块", FontFactory.GetFont(FontFactory.COURIER, 20, iTextSharp.text.Font.COURIER, new iTextSharp.text.Color(255, 0, 0))); doc.Add(chunk); //如果你希望一些块有下划线或删除线,你可以通过改变字体风格简单做到: Chunk chunk1 = new Chunk("This text is underlined", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED)); Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.STRIKETHRU)); //改变块的背景 chunk2.SetBackground(new iTextSharp.text.Color(0xFF, 0xFF, 0x00)); //上标/下标 chunk1.SetTextRise(5); doc.Add(chunk1); doc.Add(chunk2); //外部链接示例: Anchor anchor = new Anchor("website", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED, new iTextSharp.text.Color(0, 0, 255))); anchor.Reference = "http://itextsharp.sourceforge.net"; anchor.Name = "website"; //内部链接示例: Anchor anchor1 = new Anchor("This is an internal link\n\n"); anchor1.Name = "link1"; Anchor anchor2 = new Anchor("Click here to jump to the internal link\n\f"); anchor2.Reference = "#link1"; doc.Add(anchor); doc.Add(anchor1); doc.Add(anchor2); //排序列表示例: List list = new List(true, 20); list.Add(new ListItem("First line")); list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?")); list.Add(new ListItem("Third line")); doc.Add(list); //文本注释: Annotation a = new Annotation("authors", "Maybe its because I wanted to be an author myself that I wrote iText."); doc.Add(a); //包含页码没有任何边框的页脚。 iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new Phrase("This is page: "), true); footer.Border = iTextSharp.text.Rectangle.NO_BORDER; doc.Footer = footer; //Chapter对象和Section对象自动构建一个树: iTextSharp.text.Font f1 = new iTextSharp.text.Font(); f1.SetStyle(iTextSharp.text.Font.BOLD); Paragraph cTitle = new Paragraph("This is chapter 1", f1); Chapter chapter = new Chapter(cTitle, 1); Paragraph sTitle = new Paragraph("This is section 1 in chapter 1", f1); Section section = chapter.AddSection(sTitle, 1); doc.Add(chapter); //构建了一个简单的表: Table aTable = new Table(4, 4); aTable.AutoFillEmptyCells = true; aTable.AddCell("2.2", new System.Drawing.Point(2, 2)); aTable.AddCell("3.3", new System.Drawing.Point(3, 3)); aTable.AddCell("2.1", new System.Drawing.Point(2, 1)); aTable.AddCell("1.3", new System.Drawing.Point(1, 3)); doc.Add(aTable); //构建了一个不简单的表: Table table = new Table(3); table.BorderWidth = 1; table.BorderColor = new iTextSharp.text.Color(0, 0, 255); table.Cellpadding = 5; table.Cellspacing = 5; Cell cell = new Cell("header"); cell.Header = true; cell.Colspan = 3; table.AddCell(cell); cell = new Cell("example cell with colspan 1 and rowspan 2"); cell.Rowspan = 2; cell.BorderColor = new iTextSharp.text.Color(255, 0, 0); table.AddCell(cell); table.AddCell("1.1"); table.AddCell("2.1"); table.AddCell("1.2"); table.AddCell("2.2"); table.AddCell("cell test1"); cell = new Cell("big cell"); cell.Rowspan = 2; cell.Colspan = 2; cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0); table.AddCell(cell); table.AddCell("cell test2"); // 改变了单元格“big cell”的对齐方式: cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_MIDDLE; doc.Add(table); #endregion //关闭document doc.Close(); //打开PDF,看效果 //Process.Start(sourcePath); } catch (DocumentException de) { Console.WriteLine(de.Message); Console.ReadKey(); } catch (IOException io) { Console.WriteLine(io.Message); Console.ReadKey(); } }
protected override Stream Read() { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); doc.AddTitle(Title); doc.AddCreationDate(); doc.AddCreator("iTextSharp"); doc.AddAuthor("文化中国"); doc.AddSubject(f.Brief); using (MemoryStream stream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(doc, stream); writer.SetEncryption(true, null, null, PdfWriter.ALLOW_PRINTING); writer.ViewerPreferences = PdfWriter.PageModeUseOutlines; writer.PageEvent = new HeaderFooterPdfPageEventHelper(); doc.Open(); foreach (var w in f.Webcasts.Where(w => w.Script != null).OrderBy(w => w.Aired)) { Paragraph p = new Paragraph(w.Title, font); p.Alignment = 1; Chapter chapter = new Chapter(p, 1); chapter.NumberDepth = 0; chapter.BookmarkTitle = w.Title; chapter.TriggerNewPage = true; doc.Add(chapter); MatchCollection matches = regex.Matches(w.Script.Text); foreach (Match m in matches) { Chunk chunk = new Chunk(m.Groups["cont"].Value); switch (m.Groups["tag"].Value.ToLower()) { case "h1": font.Color = BaseColor.WHITE; chunk.SetBackground(BaseColor.DARK_GRAY); break; case "p": font.Color = BaseColor.BLACK; break; } chunk.Font = font; p = new Paragraph(chunk); p.SetLeading(0.0f, 2.0f); p.FirstLineIndent = 20f; p.Alignment = 0; doc.Add(p); } } doc.Close(); return new MemoryStream(stream.GetBuffer()); } }
private void CreatePdfBookMarks(List<PdfDef> pdfDocuments, string outputFile) { Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(outputFile, System.IO.FileMode.Create)); document.Open(); foreach (PdfDef pdfDocument in pdfDocuments) { String [] tiffImages = new string[pdfDocument.TiffImages.Length]; for (int i = 0; i < pdfDocument.TiffImages.Length; i++) tiffImages[i] = pdfDocument.TiffImages[i]; Chapter chapter = new Chapter(pdfDocument.ChapterTitle, pdfDocument.ChapterNumber); document.Add(chapter); for (int count = 0; count < tiffImages.Length; count++) { Bitmap bitmap = new Bitmap(tiffImages[count]); int total = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); PdfContentByte cb = writer.DirectContent; for (int k = 0; k < total; ++k) { bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k); Image image = Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp); image.ScalePercent(72f / image.DpiX * 100); image.SetAbsolutePosition(0, 0); cb.AddImage(image); document.NewPage(); } } } UpdateProperties(document); document.Close(); }
public static void CreatePDF(string directoryPath , string pdfFile, string name, ComicDownloaderSettings settings){ try { Directory.CreateDirectory(Path.GetDirectoryName(pdfFile)); } finally{} Document pdfDoc = new Document(PageSize.A4); AssemblyInfoHelper info = new AssemblyInfoHelper(typeof(PDFHelper)); pdfDoc.AddAuthor(info.Company); pdfDoc.AddCreationDate(); pdfDoc.AddTitle(name); float docw = pdfDoc.PageSize.Width; float doch = pdfDoc.PageSize.Width; PdfDate st = new PdfDate(DateTime.Today); Chapter chapter = new Chapter(new Paragraph(name), 1); try { var stream = File.Create(pdfFile); var writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); if (settings.IncludePDFIntroPage && settings.PdfIntroPagePosition == PagePosition.FirstPage) EmbedeIntroPage(pdfDoc, writer); DirectoryInfo di = new DirectoryInfo(directoryPath); var files = di.GetFiles(); if (files != null) { foreach (var fi in files) { Image img = Image.GetInstance(fi.FullName); float h = img.Height; float w = img.Width; float hp = doch / h; float wp = docw / w; ///img.ScaleToFit(docw * 1.35f, doch * 1.35f); // img.ScaleToFit(750, 550); pdfDoc.NewPage(); //pdfDoc.Add(img); PdfPTable nestedTable = new PdfPTable(1); PdfPCell cell = new PdfPCell(img); cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; nestedTable.AddCell(cell); //pdfDoc.Add(nestedTable); Section section = chapter.AddSection(0f, new Paragraph("", new Font() { Color = BaseColor.WHITE })); //section.Add(nestedTable); //pdfDoc.Add(section); pdfDoc.Add(nestedTable); } if (settings.IncludePDFIntroPage && settings.PdfIntroPagePosition == PagePosition.LastPage) EmbedeIntroPage(pdfDoc, writer); } } catch (Exception ex) { MyLogger.Log(ex); } finally { pdfDoc.Close(); } }
/// <summary> /// 保存为pdf /// </summary> /// <param name="filename"></param> public void SavePdf(string filename) { FileInfo fileinfo = new FileInfo(filename); if (fileinfo.Directory.Exists == false) Directory.CreateDirectory(fileinfo.DirectoryName); Document doc = new Document(PageSize.A5, 10, 10, 10, 10); PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create)); doc.Open(); //指定字体库,并创建字体 BaseFont baseFont = BaseFont.CreateFont( "C:\\WINDOWS\\FONTS\\SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font1 = new iTextSharp.text.Font(baseFont, 18); iTextSharp.text.Font font2 = new iTextSharp.text.Font(baseFont, 20); Chapter chapter1 = new Chapter(title, 1); chapter1.Add(new Paragraph(title, font2)); chapter1.Add(new Paragraph(auther, font1)); chapter1.Add(new Paragraph(introduction, font1)); for (int i = 0; i < catalogs.Count; i++) { Section section1 = chapter1.AddSection(catalogs[i].text); section1.Add(new Paragraph(catalogs[i].page.text, font1)); section1.TriggerNewPage = true; section1.BookmarkOpen = false; } chapter1.BookmarkOpen = false; doc.Add(chapter1); doc.Close(); }
private void ChartTypeLineStackedMarker(Chapter chapter, string imagePath) { var image = Image.GetInstance(imagePath); var pdfTable1 = new PdfPTable(2); var cell1 = new PdfPCell(ExamAnalysiseReportFormat.InsertImageParagraph(image)){BorderWidth = 0}; var cell2 = new PdfPCell(ExamAnalysiseReportFormat.InsertImageParagraph(image)) { BorderWidth = 0 }; pdfTable1.AddCell(cell1); pdfTable1.AddCell(cell2); chapter.Add(ExamAnalysiseReportFormat.InsertTableParagraph(pdfTable1)); }
/* ----------------------------------------------------------------- */ /// Run /* ----------------------------------------------------------------- */ public void Run(string path) { iTextPDF.PdfWriter.GetInstance(_doc, new System.IO.FileStream(path, System.IO.FileMode.Create)); _doc.Open(); while (_index < _parser.Elements.Count) { var element = _parser.Elements[_index]; if (element.Type == ElementType.Section && element.Depth == 1) this.AddElements(null); else { var chapter = new iText.Chapter(_chapter++); this.AddElements(chapter); _doc.Add(chapter); } } _doc.Close(); }
private Chapter GetChapter(FeedEntity entity) { Font ft = new Font(baseFT, 12); Chapter chp = new Chapter(new Paragraph(entity.Title, new Font(baseFT, 12)) { Alignment = Element.ALIGN_CENTER }, chp_idx++); chp.Add(new Paragraph(" ")); chp.Add(new Paragraph(" ")); string text = GetContent(entity); int rownum = 1; foreach (string line in text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) { try { if (line == "[code_begin]") { //ft = codeFT; ft = new Font(codeFT, 11); } else if (line == "[code_end]") { ft = new Font(baseFT, 12); } else if (line.StartsWith("[img]")) { Image img = Image.GetInstance(line.Substring(5)); if (img.Width > 40) { if (img.Width > 560) img.ScaleToFit(560, 560); img.Alignment = Element.ALIGN_CENTER; chp.Add(img); } } else if (line.Replace("\t","").StartsWith("//")) { iTextSharp.text.Font font = new iTextSharp.text.Font(codeFT,11, Font.NORMAL, BaseColor.BLUE); String line_ = line.Replace("\t", " "); chp.Add(new Paragraph(line_, font)); } else if (line.Replace("\t", "").StartsWith("/*") || line.Replace("\t", "").StartsWith("*") || line.Replace("\t", "").StartsWith("*/")) { iTextSharp.text.Font font = new iTextSharp.text.Font(codeFT, 11, Font.NORMAL, BaseColor.GREEN); String line_ = line.Replace("\t", " "); chp.Add(new Paragraph(line_, font)); } else { String line_ = line.Replace("\t", " "); chp.Add(new Paragraph(line_, ft)); } } catch { } } return chp; }
private void GenerateBatteryChartByCustVin(string TempFolderPath, string ProcessDate) { Paragraph para = new Paragraph(); Section sec = new Section(); string CustomerId = string.Empty; string CustomerName = string.Empty; string Vin = string.Empty; int VinId = 0; string Bus = string.Empty; DataTable dtCust = new DataTable(); DataTable dtVin = new DataTable(); GetData gd = new GetData(); dtCust = gd.DtGetCustomerInfo(DateTime.Parse(ProcessDate)); int i = 0; int j = 0; foreach (DataRow dRow in dtCust.Rows) { i++; j = 0; CustomerId = dRow["CustomerId"].ToString(); CustomerName = dRow["CustomerName"].ToString(); dtVin = gd.DtGetCustomerVehicleInfo(int.Parse(CustomerId), DateTime.Parse(ProcessDate)); _doc.NewPage(); //para = new Paragraph(CustomerName); //Chapter chap = new Chapter(para, i); //Section section1 = chap.AddSection(20f, "Section 1.1", 1); //_doc.Add(chap); foreach (DataRow vRow in dtVin.Rows) { j++; Vin = string.Empty; Vin = vRow["Vin"].ToString(); Bus = vRow["Bus"].ToString(); VinId = int.Parse(vRow["VinID"].ToString()); if (j > 1) { _doc.NewPage(); } //Dashboard// // sec = chap.AddSection(20f, Vin, j); //PdfPTable tableHeader = GenerateBatteryAllCustHeader(ProcessDate, CustomerName, Vin, Bus); //_doc.Add(tableHeader); para = new Paragraph(Bus.ToUpper()); Chapter chap = new Chapter(para, j); _doc.Add(chap); string imageURL_VinDash = Path.Combine(TempFolderPath, string.Format("VinDashboard_{0}.png", vRow["VinID"].ToString())); //iTextSharp.text.Image jpg_VinDash = iTextSharp.text.Image.GetInstance(imageURL_VinDash); ////Resize image depend upon your need ////jpg.ScaleToFit(chartWidth, chartHeight); //// jpg_VinHist.ScaleToFit(600f, 250f); //jpg_VinDash.ScalePercent(75f); ////Give space before image //jpg_VinDash.SpacingBefore = 10f; ////Give some space after the image //jpg_VinDash.SpacingAfter = 1f; //jpg_VinDash.Alignment = Element.ALIGN_CENTER; //_doc.Add(jpg_VinDash); PdfPTable tablebat = GenerateBatteryVinDashboard(ProcessDate, VinId); _doc.Add(tablebat); //TMaxByPacks// string imageURL_TMaxByPacks = Path.Combine(TempFolderPath, string.Format("TMaxByPacks_{0}.png", vRow["VinID"].ToString())); iTextSharp.text.Image jpg_TMaxByPacks = iTextSharp.text.Image.GetInstance(imageURL_TMaxByPacks); //Resize image depend upon your need //jpg.ScaleToFit(chartWidth, chartHeight); // jpg_VinHist.ScaleToFit(600f, 250f); jpg_TMaxByPacks.ScalePercent(60f); //Give space before image jpg_TMaxByPacks.SpacingBefore = 10f; //Give some space after the image jpg_TMaxByPacks.SpacingAfter = 1f; jpg_TMaxByPacks.Alignment = Element.ALIGN_CENTER; _doc.Add(jpg_TMaxByPacks); //CurrentByPacks// string imageURL_CurrentByPacks = Path.Combine(TempFolderPath, string.Format("CurrentByPacks_{0}.png", vRow["VinID"].ToString())); iTextSharp.text.Image jpg_CurrentByPacks = iTextSharp.text.Image.GetInstance(imageURL_CurrentByPacks); //Resize image depend upon your need //jpg.ScaleToFit(chartWidth, chartHeight); // jpg_VinHist.ScaleToFit(600f, 250f); jpg_CurrentByPacks.ScalePercent(60f); //Give space before image jpg_CurrentByPacks.SpacingBefore = 10f; //Give some space after the image jpg_CurrentByPacks.SpacingAfter = 1f; jpg_CurrentByPacks.Alignment = Element.ALIGN_CENTER; _doc.Add(jpg_CurrentByPacks); //SoCByPacks_Min// string imageURL_SoCByPacks_Min = Path.Combine(TempFolderPath, string.Format("SoCByPacks_Min_{0}.png", vRow["VinID"].ToString())); iTextSharp.text.Image jpg_SoCByPacks_Min = iTextSharp.text.Image.GetInstance(imageURL_SoCByPacks_Min); //Resize image depend upon your need //jpg.ScaleToFit(chartWidth, chartHeight); // jpg_VinHist.ScaleToFit(600f, 250f); jpg_SoCByPacks_Min.ScalePercent(60f); //Give space before image jpg_SoCByPacks_Min.SpacingBefore = 10f; //Give some space after the image jpg_SoCByPacks_Min.SpacingAfter = 1f; jpg_SoCByPacks_Min.Alignment = Element.ALIGN_CENTER; _doc.Add(jpg_SoCByPacks_Min); //SoCByPacks_Max// string imageURL_SoCByPacks_Max = Path.Combine(TempFolderPath, string.Format("SoCByPacks_Max_{0}.png", vRow["VinID"].ToString())); iTextSharp.text.Image jpg_SoCByPacks_Max = iTextSharp.text.Image.GetInstance(imageURL_SoCByPacks_Max); //Resize image depend upon your need //jpg.ScaleToFit(chartWidth, chartHeight); // jpg_VinHist.ScaleToFit(600f, 250f); jpg_SoCByPacks_Max.ScalePercent(60f); //Give space before image jpg_SoCByPacks_Max.SpacingBefore = 10f; //Give some space after the image jpg_SoCByPacks_Max.SpacingAfter = 1f; jpg_SoCByPacks_Max.Alignment = Element.ALIGN_CENTER; _doc.Add(jpg_SoCByPacks_Max); //CurrentByPacks } } }
/// <summary> /// This method deals with the starting tags. /// </summary> /// <param name="name">the name of the tag</param> /// <param name="attributes">the list of attributes</param> public void HandleStartingTags(String name, Properties attributes) { //System.err.Println("Start: " + name); if (ignore || ElementTags.IGNORE.Equals(name)) { ignore = true; return; } // maybe there is some meaningful data that wasn't between tags if (currentChunk != null) { ITextElementArray current; try { current = (ITextElementArray) stack.Pop(); } catch { if (bf == null) { current = new Paragraph("", new Font()); } else { current = new Paragraph("", new Font(this.bf)); } } current.Add(currentChunk); stack.Push(current); currentChunk = null; } // registerfont if (name.Equals("registerfont")) { FontFactory.Register(attributes); } // header if (ElementTags.HEADER.Equals(name)) { stack.Push(new HeaderFooter(attributes)); return; } // footer if (ElementTags.FOOTER.Equals(name)) { stack.Push(new HeaderFooter(attributes)); return; } // before if (name.Equals("before")) { HeaderFooter tmp = (HeaderFooter)stack.Pop(); tmp.Before = new Phrase(attributes); stack.Push(tmp); return; } // after if (name.Equals("after")) { HeaderFooter tmp = (HeaderFooter)stack.Pop(); tmp.After = new Phrase(attributes); stack.Push(tmp); return; } // chunks if (Chunk.IsTag(name)) { currentChunk = new Chunk(attributes); if (bf != null) { currentChunk.Font = new Font(this.bf); } return; } // symbols if (EntitiesToSymbol.IsTag(name)) { Font f = new Font(); if (currentChunk != null) { HandleEndingTags(ElementTags.CHUNK); f = currentChunk.Font; } currentChunk = EntitiesToSymbol.Get(attributes[ElementTags.ID], f); return; } // phrases if (Phrase.IsTag(name)) { stack.Push(new Phrase(attributes)); return; } // anchors if (Anchor.IsTag(name)) { stack.Push(new Anchor(attributes)); return; } // paragraphs and titles if (Paragraph.IsTag(name) || Section.IsTitle(name)) { stack.Push(new Paragraph(attributes)); return; } // lists if (List.IsTag(name)) { stack.Push(new List(attributes)); return; } // listitems if (ListItem.IsTag(name)) { stack.Push(new ListItem(attributes)); return; } // cells if (Cell.IsTag(name)) { stack.Push(new Cell(attributes)); return; } // tables if (Table.IsTag(name)) { Table table = new Table(attributes); float[] widths = table.ProportionalWidths; for (int i = 0; i < widths.Length; i++) { if (widths[i] == 0) { widths[i] = 100.0f / (float)widths.Length; } } try { table.Widths = widths; } catch (BadElementException bee) { // this shouldn't happen throw new Exception("", bee); } stack.Push(table); return; } // sections if (Section.IsTag(name)) { IElement previous = (IElement) stack.Pop(); Section section; section = ((Section)previous).AddSection(attributes); stack.Push(previous); stack.Push(section); return; } // chapters if (Chapter.IsTag(name)) { String value; // changed after a suggestion by Serge S. Vasiljev if ((value = (String)attributes.Remove(ElementTags.NUMBER)) != null){ chapters = int.Parse(value); } else { chapters++; } Chapter chapter = new Chapter(attributes,chapters); stack.Push(chapter); return; } // images if (Image.IsTag(name)) { try { Image img = Image.GetInstance(attributes); Object current; try { // if there is an element on the stack... current = stack.Pop(); // ...and it's a Chapter or a Section, the Image can be added directly if (current is Chapter || current is Section || current is Cell) { ((ITextElementArray)current).Add(img); stack.Push(current); return; } // ...if not, the Image is wrapped in a Chunk before it's added else { Stack newStack = new Stack(); try { while (! (current is Chapter || current is Section || current is Cell)) { newStack.Push(current); if (current is Anchor) { img.Annotation = new Annotation(0, 0, 0, 0, ((Anchor)current).Reference); } current = stack.Pop(); } ((ITextElementArray)current).Add(img); stack.Push(current); } catch { document.Add(img); } while (!(newStack.Count == 0)) { stack.Push(newStack.Pop()); } return; } } catch { // if there is no element on the stack, the Image is added to the document try { document.Add(img); } catch (DocumentException de) { throw new Exception("", de); } return; } } catch (Exception e) { throw new Exception("", e); } } // annotations if (Annotation.IsTag(name)) { Annotation annotation = new Annotation(attributes); ITextElementArray current; try { try { current = (ITextElementArray) stack.Pop(); try { current.Add(annotation); } catch { document.Add(annotation); } stack.Push(current); } catch { document.Add(annotation); } return; } catch (DocumentException de) { throw new Exception("", de); } } // newlines if (IsNewline(name)) { ITextElementArray current; try { current = (ITextElementArray) stack.Pop(); current.Add(Chunk.NEWLINE); stack.Push(current); } catch { if (currentChunk == null) { try { document.Add(Chunk.NEWLINE); } catch (DocumentException de) { throw new Exception("", de); } } else { currentChunk.Append("\n"); } } return; } // newpage if (IsNewpage(name)) { ITextElementArray current; try { current = (ITextElementArray) stack.Pop(); Chunk newPage = new Chunk(""); newPage.SetNewPage(); if (bf != null) { newPage.Font = new Font(this.bf); } current.Add(newPage); stack.Push(current); } catch { document.NewPage(); } return; } // documentroot if (IsDocumentRoot(name)) { String value; // pagesize and orientation specific code suggested by Samuel Gabriel // Updated by Ricardo Coutinho. Only use if set in html! Rectangle pageSize = null; String orientation = null; foreach (string key in attributes.Keys) { value = attributes[key]; // margin specific code suggested by Reza Nasiri if (Util.EqualsIgnoreCase(ElementTags.LEFT, key)) leftMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo); if (Util.EqualsIgnoreCase(ElementTags.RIGHT, key)) rightMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo); if (Util.EqualsIgnoreCase(ElementTags.TOP, key)) topMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo); if (Util.EqualsIgnoreCase(ElementTags.BOTTOM, key)) bottomMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo); if (ElementTags.PAGE_SIZE.Equals(key)) { pageSize = (Rectangle)typeof(PageSize).GetField(value).GetValue(null); } else if (ElementTags.ORIENTATION.Equals(key)) { if ("landscape".Equals(value)) { orientation = "landscape"; } } else { document.Add(new Meta(key, value)); } } if(pageSize != null) { if ("landscape".Equals(orientation)) { pageSize = pageSize.Rotate(); } document.SetPageSize(pageSize); } document.SetMargins(leftMargin, rightMargin, topMargin, bottomMargin); if (controlOpenClose) document.Open(); } }
private Chapter GetChapter(FeedEntity entity) { Font ft = new Font(baseFT, 12); Chapter chp = new Chapter(new Paragraph(entity.Title, new Font(baseFT, 18)) { Alignment = Element.ALIGN_CENTER }, chp_idx++); chp.Add(new Paragraph(" ")); chp.Add(new Paragraph(" ")); string text = GetContent(entity); foreach (string line in text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) { try { if (line == "[code_begin]") { ft = codeFT; } else if (line == "[code_end]") { ft = new Font(baseFT, 12); } else if (line.StartsWith("[img]")) { Image img = Image.GetInstance(line.Substring(5)); if (img.Width > 40) { if (img.Width > 560) img.ScaleToFit(560, 560); img.Alignment = Element.ALIGN_CENTER; chp.Add(img); } } else { chp.Add(new Paragraph(line, ft)); } } catch { } } return chp; }
public static void ExportTestSettings(Chapter chapter, Font font, int flowCount, long recordCount, float randomness) { Section settings = chapter.AddSection(new Paragraph("Test settings.", font)); string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; settings.Add(new Paragraph(String.Format("\t \t Benchmark - {0}", version))); settings.Add(new Paragraph(String.Format("\t \t Export date - {0}", DateTime.Now))); settings.Add(new Chunk("\n")); Section testSettings = chapter.AddSection(new Paragraph("Settings.", font)); testSettings.Add(new Paragraph(String.Format("\t \t Flow count - {0}", flowCount))); testSettings.Add(new Paragraph(String.Format("\t \t Record count - {0}", recordCount))); testSettings.Add(new Paragraph(String.Format("\t \t Randomness - {0}%", randomness * 100))); testSettings.Add(new Paragraph(String.Format("\t \t Key type - {0}", randomness == 0f ? KeysType.Sequential : KeysType.Random))); testSettings.Add(new Chunk("\n")); }
static void Main(string[] args) { string folder = @"C:\Users\Administrator\Desktop\TESTIMGS"; string pdf = @"C:\Users\Administrator\Desktop\generatedpdf.pdf"; Document pdfDoc = new Document(PageSize.A4,5f,5f,5f,5f); float docw = pdfDoc.PageSize.Width; float doch = pdfDoc.PageSize.Height; PdfDate st = new PdfDate(DateTime.Today); Chapter chapter = new Chapter(new Paragraph("Dragon ball chapter 1"),1); try { var stream = File.Create(pdf); var writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); DirectoryInfo di = new DirectoryInfo(folder); var files = di.GetFiles(); if (files != null) { foreach (var fi in files) { // img.ScaleToFit(750, 550); pdfDoc.NewPage(); Image img = Image.GetInstance(fi.FullName); float h = img.Height; float w = img.Width; float hp = doch / h; float wp = docw / w; //if (img.Width > docw*1.15f) { // img.ScaleToFit(docw*1.35f, doch*1.35f); //img.SetAbsolutePosition(5, 5); // img.ScaleToFit(pdfDoc.PageSize.Width - 10, pdfDoc.PageSize.Width - 10); } //Section section = chapter.AddSection(0f, "Pages", 1); //pdfDoc.Add(chapter); PdfPTable nestedTable = new PdfPTable(1); PdfPCell cell = new PdfPCell(img); cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; nestedTable.AddCell(cell); //pdfDoc.Add(nestedTable); Section section = chapter.AddSection(0f,new Paragraph("", new Font() { Color = BaseColor.WHITE })); section.Add(nestedTable); pdfDoc.Add(section); //pdfDoc.Add(img); //pdfDoc.Add(new iTextSharp.text.Jpeg(new Uri(fi.FullName))); } } } catch (Exception ex) { } finally { //pdfDoc.Add(chapter); pdfDoc.Close(); Process.Start(pdf); } }
public void CreateTaggedPdf11() { InitializeDocument("11"); Chapter c = new Chapter( new Paragraph("First chapter", new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLUE)), 1); c.TriggerNewPage = false; c.Indentation = 40; Section s1 = c.AddSection(new Paragraph("First section of a first chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; Section s2 = s1.AddSection(new Paragraph("First subsection of a first section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a first section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a first section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s1 = c.AddSection(new Paragraph("Second section of a first chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a second section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a second section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a second section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s1 = c.AddSection(new Paragraph("Third section of a first chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a third section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a third section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a third section of a first chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); document.Add(c); c = new Chapter( new Paragraph("Second chapter", new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLUE)), 2); c.TriggerNewPage = false; c.Indentation = 40; s1 = c.AddSection(new Paragraph("First section of a second chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a first section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a first section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a first section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s1 = c.AddSection(new Paragraph("Second section of a second chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a second section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a second section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a second section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s1 = c.AddSection(new Paragraph("Third section of a second chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a third section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a third section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a third section of a second chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); document.Add(c); c = new Chapter( new Paragraph("Third chapter", new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLUE)), 3); c.TriggerNewPage = false; c.Indentation = 40; s1 = c.AddSection(new Paragraph("First section of a third chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a first section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a first section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a first section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s1 = c.AddSection(new Paragraph("Second section of a third chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a second section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a second section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a second section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s1 = c.AddSection(new Paragraph("Third section of a third chapter", new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, BaseColor.BLUE))); s1.Indentation = 20; s2 = s1.AddSection(new Paragraph("First subsection of a third section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Second subsection of a third section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); s2 = s1.AddSection(new Paragraph("Third subsection of a third section of a third chapter", new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE))); s2.Indentation = 10; s2.Add(new Paragraph("Some text...")); document.Add(c); document.Close(); int[] nums = new int[] {114, 60}; CheckNums(nums); CompareResults("11"); }
// --------------------------------------------------------------------------- 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); } }