static Rect RenderTableHeader(C1PdfDocument pdf, Font font, Rect rc, string[] fields) { // calculate cell width (same for all columns) Rect rcCell = rc; rcCell.Width = rc.Width / fields.Length; rcCell.Height = 0; // calculate cell height (max of all columns) foreach (string field in fields) { var height = pdf.MeasureString(field, font, rcCell.Width).Height; rcCell.Height = Math.Max(rcCell.Height, height); } rcCell.Height += 6; // add 6 point margin // render header cells var fmt = new StringFormat(); fmt.LineAlignment = VerticalAlignment.Center; foreach (string field in fields) { pdf.FillRectangle(Colors.Black, rcCell); pdf.DrawString(field, font, Colors.White, rcCell, fmt); rcCell = PdfUtils.Offset(rcCell, rcCell.Width, 0); } // update rectangle and return it return(PdfUtils.Offset(rc, 0, rcCell.Height)); }
public static async void Save(this C1PdfDocument pdf) { FileSavePicker picker = new FileSavePicker(); picker.FileTypeChoices.Add(Strings.FileTypeChoicesTip, new List <string>() { ".pdf" }); picker.DefaultFileExtension = ".pdf"; picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { await pdf.SaveAsync(file); MessageDialog dlg = new MessageDialog(Strings.SaveLocationTip + " " + file.Path, "PdfSamples"); dlg.Commands.Add(new UICommand("Open", new UICommandInvokedHandler((args) => { // to open the created file (using file extension) var success = Launcher.LaunchFileAsync(file); }))); dlg.Commands.Add(new UICommand("Cancel")); dlg.CancelCommandIndex = 2; await dlg.ShowAsync(); } }
private void Button_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "PDF files (*.pdf)|*.pdf"; //var t = dlg.ShowDialog(); if (dlg.ShowDialog().Value) { // create pdf document var pdf = new C1PdfDocument(); pdf.Landscape = true; pdf.Compression = CompressionLevel.NoCompression; // render all grids into pdf document var options = new PdfExportOptions(); options.ScaleMode = ScaleMode.ActualSize; GridExport.RenderGrid(pdf, _flex1, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex2, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex3, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex4, options); // save document using (var stream = dlg.OpenFile()) { pdf.Save(stream); } } }
private void makeDocument() { // start a new document C1PdfDocument pdf = new C1PdfDocument(); string name = Thread.CurrentThread.Name; // with two fonts Font font1 = new Font("Tahoma", 10); Font font2 = new Font("Tahoma", 10, FontStyle.Italic); // create document pdf.Clear(); RectangleF rc = pdf.PageRectangle; rc.Inflate(-72, -72); while (rc.Y < pdf.PageRectangle.Bottom - 72) { pdf.DrawString("Hello buddy. This is thread " + name, font1, Brushes.Red, rc); rc.Y += 12; pdf.DrawString("Hello again. Same thread " + name, font2, Brushes.Blue, rc); rc.Y += 12; pdf.DrawLine(Pens.ForestGreen, rc.X, rc.Y, rc.Right, rc.Y); // let other threads work Thread.Sleep(0); } // save document pdf.Save(string.Format(@"c:\temp\test{0}.pdf", name)); }
static void CreateDocumentQuotes(C1PdfDocument pdf) { // calculate page rect (discounting margins) Rect rcPage = PdfUtils.PageRectangle(pdf); Rect rc = rcPage; // initialize output parameters Font hdrFont = new Font("Arial", 14, PdfFontStyle.Bold); Font titleFont = new Font("Arial", 24, PdfFontStyle.Bold); Font txtFont = new Font("Times New Roman", 10, PdfFontStyle.Italic); // add title rc = PdfUtils.RenderParagraph(pdf, pdf.DocumentInfo.Title, titleFont, rcPage, rc); // build document foreach (string s in GetQuotes()) { string[] authorQuote = s.Split('\t'); // render header (author) var author = authorQuote[0]; rc.Y += 20; rc = PdfUtils.RenderParagraph(pdf, author, hdrFont, rcPage, rc, true); // render body text (quote) string text = authorQuote[1]; rc.X = rcPage.X + 36; // << indent body text by 1/2 inch rc.Width = rcPage.Width - 40; rc = PdfUtils.RenderParagraph(pdf, text, txtFont, rcPage, rc); rc.X = rcPage.X; // << restore indent rc.Width = rcPage.Width; rc.Y += 12; // << add 12pt spacing after each quote } }
private void Button_Click(object sender, RoutedEventArgs e) { // get stream to save to var dlg = new SaveFileDialog(); dlg.DefaultExt = ".pdf"; var dr = dlg.ShowDialog(); if (!dr.HasValue || !dr.Value) { return; } // get sender button var btn = sender as Button; // create document var pdf = new C1PdfDocument(PaperKind.Letter); pdf.Clear(); // set document info var di = pdf.DocumentInfo; di.Author = "ComponentOne"; di.Subject = "C1.WPF.Pdf demo."; di.Title = "Experimental VisualTree Exporter for PDF"; // walk visual tree CreateDocumentVisualTree(pdf, content); // render footers // this reopens each page and adds content to them (now we know the page count). var font = new Font("Arial", 8, PdfFontStyle.Bold); var fmt = new StringFormat(); fmt.Alignment = HorizontalAlignment.Right; fmt.LineAlignment = VerticalAlignment.Bottom; for (int page = 0; page < pdf.Pages.Count; page++) { pdf.CurrentPage = page; var text = string.Format("C1.WPF.Pdf: {0}, page {1} of {2}", di.Title, page + 1, pdf.Pages.Count); pdf.DrawString( text, font, Colors.DarkGray, PdfUtils.Inflate(pdf.PageRectangle, -72, -36), fmt); } // save document using (var stream = dlg.OpenFile()) { pdf.Save(stream); } MessageBox.Show("Pdf Document saved to " + dlg.SafeFileName); }
private void AddTextToPage(string text, string key, C1PdfDocument doc) { int x = 0; int y = 0; int fontsize = 0; string description = ""; GetTextAttributes(key, out x, out y, out fontsize, out description); text = description + text; // Add the text. PointF startPoint = new PointF(x, y); Font fnt; string fontname = "Ariel"; fontname = ConfigurationManager.AppSettings["fontname"]; if (fontname == null) { fontname = "Ariel"; } fnt = new Font(fontname, fontsize); using (fnt) { doc.DrawString(text, fnt, Brushes.Blue, startPoint); } }
// measure a paragraph, skip a page if it won't fit, render it into a rectangle, // and update the rectangle for the next paragraph. // // optionally mark the paragraph as an outline entry and as a link target. // // this routine will not break a paragraph across pages. for that, see the Text Flow sample. // public static Rect RenderParagraph(C1PdfDocument pdf, string text, Font font, Rect rcPage, Rect rc, bool outline, bool linkTarget) { // if it won't fit this page, do a page break rc.Height = pdf.MeasureString(text, font, rc.Width).Height; if (rc.Bottom > rcPage.Bottom) { pdf.NewPage(); rc.Y = rcPage.Top; } // draw the string pdf.DrawString(text, font, Colors.Black, rc); // show bounds (mainly to check word wrapping) //pdf.DrawRectangle(Pens.Sienna, rc); // add headings to outline if (outline) { pdf.DrawLine(new Pen(Colors.Black), rc.X, rc.Y, rc.Right, rc.Y); pdf.AddBookmark(text, 0, rc.Y); } // add link target if (linkTarget) { pdf.AddTarget(text, rc); } // update rectangle for next time rc.Y += rc.Height; //rc.Offset(0, rc.Height); return(rc); }
/// <summary> /// Create C1Pdf document. /// </summary> /// <returns>The C1Pdf document.</returns> internal static C1PdfDocument CreatePdfDocument() { var pdf = new C1PdfDocument(PaperKind.Letter); pdf.ConformanceLevel = PdfAConformanceLevel.PdfA2b; return(pdf); }
async Task CreateDocumentImages(C1PdfDocument pdf) { // calculate page rect (discounting margins) var rcPage = PdfUtils.PageRectangle(pdf); InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream(); // title Font font = new Font("Segoe UI Light", 16, PdfFontStyle.Italic); pdf.DrawString(Strings.ImagesDocumentTitle, font, Colors.Black, new Rect(72, 72, 400, 100)); // load image into writeable bitmap WriteableBitmap wb = new WriteableBitmap(880, 660); var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///PdfSamplesLib/Assets/pic.jpg")); wb.SetSource(await file.OpenReadAsync()); // simple draw image var rcPic = new Rect(72, 100, wb.PixelWidth / 5.0, wb.PixelHeight / 5.0); pdf.DrawImage(wb, rcPic); // draw on page preserving aspect ratio var delta = 100.0; rcPic = new Rect(new Point(delta, delta), new Point(rcPage.Width - delta, rcPage.Height - delta)); pdf.DrawImage(wb, rcPic, ContentAlignment.MiddleCenter, Stretch.Uniform); // translucent rectangle var clr = Color.FromArgb(50, 0, 255, 0); pdf.FillRectangle(clr, new Rect(200, 200, 300, 400)); }
// add text box field for fields of the PDF document // with common parameters and default names. // static PdfTextBox RenderTextBox(C1PdfDocument pdf, string text, Font font, Rect rc, Color back, string toolTip) { // create string name = string.Format("ACFTB{0}", _textBoxCount + 1); PdfTextBox textBox = new PdfTextBox(); // default border //textBox.BorderWidth = 3f / 4; textBox.BorderStyle = FieldBorderStyle.Solid; textBox.BorderColor = Colors.DarkGray; // parameters textBox.Font = font; textBox.Name = name; textBox.DefaultText = text; textBox.Text = text; textBox.ToolTip = string.IsNullOrEmpty(toolTip) ? string.Format("{0} ({1})", text, name) : toolTip; if (back != Colors.Transparent) { textBox.BackColor = back; } // add pdf.AddField(textBox, rc); _textBoxCount++; // done return(textBox); }
// add radio button box field for fields of the PDF document // with common parameters and default names. // public static PdfRadioButton RenderRadioButton(C1PdfDocument pdf, bool value, string group, string text, Font font, Rect rc, Color back, string toolTip) { // create string name = string.IsNullOrEmpty(group) ? "ACFRGR" : group; PdfRadioButton radioButton = new PdfRadioButton(); // parameters radioButton.Name = name; radioButton.DefaultValue = value; radioButton.Value = value; radioButton.ToolTip = string.IsNullOrEmpty(toolTip) ? string.Format("{0} ({1})", text, name) : toolTip; if (back != Colors.Transparent) { radioButton.BackColor = back; } // add var radioSize = font.Size; var radioTop = rc.Top + (rc.Height - radioSize) / 2; pdf.AddField(radioButton, new Rect(rc.Left, radioTop, radioSize, radioSize)); _radioButtonCount++; // text for radio button field var x = rc.Left + radioSize + 1.0f; var y = rc.Top + (rc.Height - radioSize - 1.0f) / 2; pdf.DrawString(text, new Font(font.Name, radioSize, font.Style), Colors.Black, new Point(x, y)); // done return(radioButton); }
// add list box field for fields of the PDF document // with common parameters and default names. // static PdfListBox RenderListBox(C1PdfDocument pdf, string[] list, int activeIndex, Font font, Rect rc, Color back, string toolTip) { // create string name = string.Format("ACFLB{0}", _listBoxCount + 1); PdfListBox listBox = new PdfListBox(); // default border listBox.BorderWidth = FieldBorderWidth.Thin; listBox.BorderStyle = FieldBorderStyle.Solid; listBox.BorderColor = Colors.DarkGray; // array foreach (string text in list) { listBox.Items.Add(text); } // parameters listBox.Font = font; listBox.Name = name; listBox.DefaultValue = activeIndex; listBox.Value = activeIndex; listBox.ToolTip = string.IsNullOrEmpty(toolTip) ? string.Format("{0} ({1})", string.Format("Count = {0}", listBox.Items.Count), name) : toolTip; if (back != Colors.Transparent) { listBox.BackColor = back; } // add pdf.AddField(listBox, rc); _listBoxCount++; // done return(listBox); }
// add push button box field for fields of the PDF document // with common parameters and default names. // public static PdfPushButton RenderPushButton(C1PdfDocument pdf, string text, Font font, Rect rc, Color back, Color fore, string toolTip, Image image, ButtonLayout layout) { // create string name = string.Format("ACFPB{0}", _pushButtonCount + 1); PdfPushButton pushButton = new PdfPushButton(); // parameters pushButton.Name = name; pushButton.DefaultValue = text; pushButton.Value = text; pushButton.Font = font; pushButton.ToolTip = string.IsNullOrEmpty(toolTip) ? string.Format("{0} ({1})", text, name) : toolTip; if (back != Colors.Transparent) { pushButton.BackColor = back; } if (fore != Colors.Transparent) { pushButton.ForeColor = fore; } // icon if (image != null) { // pushButton.Image = image; // pushButton.Layout = layout; } // add pdf.AddField(pushButton, rc); _pushButtonCount++; // done return(pushButton); }
public static void SetDocumentInfo(this C1PdfDocument pdf, string title) { // set document info var di = pdf.DocumentInfo; di.Author = Strings.DocumentAuthor; di.Subject = Strings.DocumentSubject; di.Title = title; // render footers // this reopens each page and adds content to them (now we know the page count). var font = new Font("Arial", 8, PdfFontStyle.Bold); var fmt = new StringFormat(); fmt.Alignment = HorizontalAlignment.Right; fmt.LineAlignment = VerticalAlignment.Bottom; for (int page = 0; page < pdf.Pages.Count; page++) { pdf.CurrentPage = page; var text = string.Format(Strings.Documentfooter, di.Title, page + 1, pdf.Pages.Count); pdf.DrawString( text, font, Colors.DarkGray, PdfUtils.Inflate(pdf.PageRectangle, -72, -36), fmt); } }
public TOCPage() { this.InitializeComponent(); this.Loaded += TOCPage_Loaded; flexViewer.DocumentSource = pdfDocSource; pdf = PdfUtils.CreatePdfDocument(); }
public BasicTextPage() { this.InitializeComponent(); this.Loaded += BasicText_Loaded; pdf = PdfUtils.CreatePdfDocument(); flexViewer.DocumentSource = pdfDocSource; }
// get the current page rectangle (depends on paper size) // and apply a 1" margin all around it. public static Rect GetPageRect(C1PdfDocument pdf) { var rcPage = pdf.PageRectangle; rcPage = new Rect(rcPage.Left + 72, rcPage.Top + 72, rcPage.Width - 144, rcPage.Height - 144); //rcPage.Inflate(-72, -72); return(rcPage); }
public static MemoryStream SaveToStream(this C1PdfDocument pdf) { MemoryStream ms = new MemoryStream(); pdf.Save(ms); ms.Seek(0, SeekOrigin.Begin); return(ms); }
public static Rect PageRectangle(this C1PdfDocument pdf, Thickness pageMargins) { Rect rc = pdf.PageRectangle; double left = Math.Min(rc.Width, rc.Left + pageMargins.Left); double top = Math.Min(rc.Height, rc.Top + pageMargins.Top); double width = Math.Max(0, rc.Width - (pageMargins.Left + pageMargins.Right)); double height = Math.Max(0, rc.Height - (pageMargins.Top + pageMargins.Bottom)); return(new Rect(left, top, width, height)); }
static Rect RenderTableRow(C1PdfDocument pdf, Font font, Font hdrFont, Rect rcPage, Rect rc, string[] fields, DataRow dr) { // calculate cell width (same for all columns) Rect rcCell = rc; rcCell.Width = rc.Width / fields.Length; rcCell.Height = 0; // calculate cell height (max of all columns) rcCell = PdfUtils.Inflate(rcCell, -4, 0); foreach (string field in fields) { string text = dr[field].ToString(); var height = pdf.MeasureString(text, font, rcCell.Width).Height; rcCell.Height = Math.Max(rcCell.Height, height); } rcCell = PdfUtils.Inflate(rcCell, 4, 0); // add 4 point margin rcCell.Height += 2; // break page if we have to if (rcCell.Bottom > rcPage.Bottom) { pdf.NewPage(); rc = RenderTableHeader(pdf, hdrFont, rcPage, fields); rcCell.Y = rc.Y; } // center vertically just to show how StringFormat fmt = new StringFormat(); fmt.LineAlignment = VerticalAlignment.Center; // render data cells foreach (string field in fields) { // get content string text = dr[field].ToString(); // set horizontal alignment double d; fmt.Alignment = (double.TryParse(text, NumberStyles.Any, CultureInfo.CurrentCulture, out d)) ? HorizontalAlignment.Right : HorizontalAlignment.Left; // render cell pdf.DrawRectangle(Colors.LightGray, rcCell); rcCell = PdfUtils.Inflate(rcCell, -4, 0); pdf.DrawString(text, font, Colors.Black, rcCell, fmt); rcCell = PdfUtils.Inflate(rcCell, 4, 0); rcCell = PdfUtils.Offset(rcCell, rcCell.Width, 0); } // update rectangle and return it return(PdfUtils.Offset(rc, 0, rcCell.Height)); }
public static void SavePdf(C1FlexGrid flex, Stream s, PdfExportOptions options) { var pdf = new C1PdfDocument(); options.KnownPageCount = false; RenderGrid(pdf, flex, options); // save the PDF document and close the stream pdf.Save(s); s.Close(); }
public RenderUIPage() { this.InitializeComponent(); List <string> comboItems = new List <string>(); comboItems.Add(PdfSamples.Strings.ComboBoxItem1_Content); comboItems.Add(PdfSamples.Strings.ComboBoxItem2_Content); combo.ItemsSource = comboItems; flexViewer.DocumentSource = pdfDocSource; pdf = PdfUtils.CreatePdfDocument(); }
static void CreateDocumentPaperSizes(C1PdfDocument pdf) { // add title Font titleFont = new Font("Tahoma", 24, PdfFontStyle.Bold); Rect rc = PdfUtils.PageRectangle(pdf); PdfUtils.RenderParagraph(pdf, pdf.DocumentInfo.Title, titleFont, rc, rc, false); // create constant font and StringFormat objects Font font = new Font("Tahoma", 18); StringFormat sf = new StringFormat(); sf.Alignment = HorizontalAlignment.Center; sf.LineAlignment = VerticalAlignment.Center; // create one page with each paper size bool firstPage = true; foreach (PaperKind pk in Enum.GetValues(typeof(PaperKind))) { // Silverlight doesn't have Enum.GetValues //PaperKind pk = fi; // skip custom size if (pk == PaperKind.Custom) { continue; } // add new page for every page after the first one if (!firstPage) { pdf.NewPage(); } firstPage = false; // set paper kind and orientation pdf.PaperKind = pk; pdf.Landscape = !pdf.Landscape; // draw some content on the page rc = PdfUtils.PageRectangle(pdf); rc = PdfUtils.Inflate(rc, -6, -6); string text = string.Format(Strings.StringFormatTwoArg, pdf.PaperKind, pdf.Landscape); pdf.DrawString(text, font, Colors.Black, rc, sf); pdf.DrawRectangle(Colors.Black, rc); } //foreach (var fi in typeof(PaperKind).GetTypeInfo().GetFields(BindingFlags.Static | BindingFlags.Public)) //{ //} }
// ** event handlers public void Save(string fileName) { // create new pdf document var pdf = new C1PdfDocument(); // add pages to document for (int page = 0; page < _images.Count; page++) { DrawPageImage(pdf, page); } // done pdf.Save(fileName); }
/// <summary> /// Shows how to position and align text /// </summary> static void CreateDocumentText(C1PdfDocument pdf) { // use landscape for more impact pdf.Landscape = true; // measure and show some text var text = Strings.DocumentBasicText; var font = new Font("Segoe UI Light", 12, PdfFontStyle.Italic); // create StringFormat used to set text alignment and line spacing var fmt = new StringFormat(); fmt.LineSpacing = -1.5; // 1.5 char height fmt.Alignment = HorizontalAlignment.Center; // measure it var sz = pdf.MeasureString(text, font, 72 * 3, fmt); var rc = new Rect(pdf.PageRectangle.Width / 2, 72, sz.Width, sz.Height); rc = PdfUtils.Offset(rc, 110, 0); // draw a rounded frame rc = PdfUtils.Inflate(rc, 0, 0); pdf.FillRectangle(Colors.Teal, rc, new Size(0, 0)); //pdf.DrawRectangle(new Pen(Colors.DarkGray, 5), rc, new Size(0, 0)); rc = PdfUtils.Inflate(rc, -10, -10); // draw the text //pdf.RotateAngle = 90; pdf.DrawString(text, font, Colors.White, rc, fmt); //pdf.RotateAngle = 0; // point in center for rotate the text rc = pdf.PageRectangle; var pt = new Point(rc.X + rc.Width / 2, rc.Y + rc.Height / 2); // rotate the string in small increments var step = 6; text = Strings.DocumentBasicText2; for (int i = 0; i <= 360; i += step) { pdf.RotateAngle = i; var s = string.Format(text, i); font = new Font("Courier New", 8 + i / 30.0, PdfFontStyle.Bold); byte b = (byte)(255 * (1 - i / 360.0)); pdf.DrawString(s, font, Color.FromArgb(0xff, b, b, b), pt); } }
//--------------------------------------------------------------------------------- #region ** images static void CreateDocumentImages(C1PdfDocument pdf) { // calculate page rect (discounting margins) Rect rcPage = PdfUtils.PageRectangle(pdf); // load image into writeable bitmap BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = DataAccess.GetStream("borabora.jpg"); bi.EndInit(); var wb = new WriteableBitmap(bi); // center image on page preserving aspect ratio pdf.DrawImage(wb, rcPage, ContentAlignment.MiddleCenter, Stretch.Uniform); }
private RectangleF RenderMultiPageImage(ref C1PdfDocument c1pdf, RectangleF rcPage, RectangleF rc, string fileName, Fax fax, bool addMetaText) { //Image img = Image.FromFile(fileName); MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileName)); Image img = Image.FromStream(ms); FrameDimension oDimension = new FrameDimension(img.FrameDimensionsList[0]); int FrameCount = img.GetFrameCount(oDimension); for (int i = 0; i < FrameCount; i++) { // calculate image height // based on image size and page size rc.Height = Math.Min(img.Height / 96f * 72, rcPage.Height); // skip page if necessary if (rc.Bottom > rcPage.Bottom) { c1pdf.NewPage(); rc.Y = rcPage.Y; } // draw solid background (mainly to see transparency) rc.Inflate(+2, +2); c1pdf.FillRectangle(Brushes.White, rc); rc.Inflate(-2, -2); // draw image (keep aspect ratio) img.SelectActiveFrame(oDimension, i); string fn = System.IO.Path.GetFileName(fileName); fn = _workingFolder + fn.Substring(0, fn.Length - 4) + "-" + i + ".tif"; img.Save(fn); //Image img1 = Image.FromFile(fn); MemoryStream ms1 = new MemoryStream(File.ReadAllBytes(fn)); Image img1 = Image.FromStream(ms1); c1pdf.DrawImage(img1, rc, ContentAlignment.MiddleCenter, ImageSizeModeEnum.Scale); // update rectangle rc.Y = rc.Bottom + 20; if ((i == 0) && (addMetaText == true)) { AddMetaText(c1pdf, fax); } } return(rc); }
//--------------------------------------------------------------------------------- #region ** text static void CreateDocumentText(C1PdfDocument pdf) { // use landscape for more impact pdf.Landscape = true; // measure and show some text var text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; var font = new Font("Times New Roman", 9, PdfFontStyle.Italic); // create StringFormat used to set text alignment and line spacing var fmt = new StringFormat(); fmt.LineSpacing = -1.5; // 1.5 char height fmt.Alignment = HorizontalAlignment.Center; // measure it var sz = pdf.MeasureString(text, font, 72 * 3, fmt); var rc = new Rect(pdf.PageRectangle.Width / 2, 72, sz.Width, sz.Height); rc = PdfUtils.Offset(rc, 72, 0); // draw a rounded frame rc = PdfUtils.Inflate(rc, 10, 10); pdf.FillRectangle(Colors.Black, rc, new Size(30, 30)); pdf.DrawRectangle(new Pen(Colors.Red, 4), rc, new Size(30, 30)); rc = PdfUtils.Inflate(rc, -10, -10); // draw the text pdf.DrawString(text, font, Colors.White, rc, fmt); // point in center for rotate the text rc = pdf.PageRectangle; var pt = new Point(rc.Location.X + rc.Width / 2, rc.Location.Y + rc.Height / 2); // rotate the string in small increments var step = 6; text = "PDF works in WPF!"; for (int i = 0; i <= 360; i += step) { pdf.RotateAngle = i; font = new Font("Courier New", 8 + i / 30.0, PdfFontStyle.Bold); byte b = (byte)(255 * (1 - i / 360.0)); pdf.DrawString(text, font, Color.FromArgb(0xff, b, b, b), pt); } }
private void OnExportClick(object sender, EventArgs e) { C1PdfDocument imageToPdf = new C1PdfDocument(); List <Image> images = new List <Image>(); foreach (Tile tile in imageTileControl.Groups[0].Tiles) { if (tile.Checked) { images.Add(tile.Image); } } if (images.Count <= 0) { MessageBox.Show(Properties.Resources.no_images_selected, Properties.Resources.dialog_alert); return; } SaveFileDialog saveFile = new SaveFileDialog(); saveFile.DefaultExt = "pdf"; saveFile.Filter = "PDF files (*.pdf)|*.pdf*"; if (saveFile.ShowDialog() == DialogResult.OK) { try { ConvertToPdf(images, imageToPdf); Console.WriteLine(saveFile.FileName); imageToPdf.Save(saveFile.FileName); DialogResult dialogResult = MessageBox.Show(saveFile.FileName + " " + Properties.Resources.saved_successfully, Properties.Resources.dialog_success, MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { System.Diagnostics.Process.Start(saveFile.FileName); } } catch (Exception e1) { Console.WriteLine(e1.StackTrace); MessageBox.Show(e1.Message, Properties.Resources.dialog_error); } } else { Console.WriteLine("Operation Cancelled"); } }
static void CreateDocumentText(C1PdfDocument pdf) { // use landscape for more impact pdf.Landscape = true; // measure and show some text var text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; var font = new Font("Times New Roman", 9, PdfFontStyle.Italic); // create StringFormat used to set text alignment and line spacing var fmt = new StringFormat(); fmt.LineSpacing = -1.5; // 1.5 char height fmt.Alignment = HorizontalAlignment.Center; // measure it var sz = pdf.MeasureString(text, font, 72 * 3, fmt); var rc = new Rect(pdf.PageRectangle.Width / 2, 72, sz.Width, sz.Height); rc = PdfUtils.Offset(rc, 72, 0); // draw a rounded frame rc = PdfUtils.Inflate(rc, 10, 10); pdf.FillRectangle(Colors.Black, rc, new Size(30, 30)); pdf.DrawRectangle(new Pen(Colors.Red, 4), rc, new Size(30, 30)); rc = PdfUtils.Inflate(rc, -10, -10); // draw the text pdf.DrawString(text, font, Colors.White, rc, fmt); // now draw some text rotating about the center of the page rc = pdf.PageRectangle; rc = PdfUtils.Offset(rc, rc.Width / 2, rc.Height / 2); // build StringFormat used to rotate the text fmt = new StringFormat(); // rotate the string in small increments var step = 6; text = "PDF works in WPF!"; for (int i = 0; i <= 360; i += step) { fmt.Angle = i; font = new Font("Courier New", 8 + i / 30.0, PdfFontStyle.Bold); byte b = (byte)(255 * (1 - i / 360.0)); pdf.DrawString(text, font, Color.FromArgb(0xff, b, b, b), rc, fmt); } }
// export the grid to a PDF file void SavePdf(Stream s, string documentName) { #if false // get root element to lay out the PDF pages Panel root = null; for (var parent = _flex.Parent as FrameworkElement; parent != null; parent = parent.Parent as FrameworkElement) { if (parent is Panel) { root = parent as Panel; } } // create pdf document var pdf = new C1PdfDocument(PaperKind.Letter, false); // get page size var rc = pdf.PageRectangle; var m = new Thickness(96, 96, 96 / 2, 96 / 2); var scaleMode = ScaleMode.ActualSize; // create panel to hold elements while they render var pageTemplate = new PageTemplate(); pageTemplate.Width = rc.Width; pageTemplate.Height = rc.Height; pageTemplate.SetPageMargin(m); root.Children.Add(pageTemplate); // render grid into PDF document var sz = new Size(rc.Width - m.Left - m.Right, rc.Height - m.Top - m.Bottom); var pages = _flex.GetPageImages(scaleMode, sz, 100); for (int i = 0; i < pages.Count; i++) { // skip a page when necessary if (i > 0) { pdf.NewPage(); } // set content pageTemplate.PageContent.Child = pages[i]; pageTemplate.PageContent.Stretch = System.Windows.Media.Stretch.Uniform; // set header/footer text pageTemplate.HeaderLeft.Text = documentName; pageTemplate.FooterRight.Text = string.Format("Page {0} of {1}", i + 1, pages.Count); // measure page element pageTemplate.Measure(new Size(rc.Width, rc.Height)); pageTemplate.UpdateLayout(); // add page element to PDF pdf.DrawElement(pageTemplate, rc); } // done with template root.Children.Remove(pageTemplate); // save the PDF document pdf.Save(s); s.Close(); #endif }
static void CreateDocumentTOC(C1PdfDocument pdf) { // create pdf document pdf.DocumentInfo.Title = "Document with Table of Contents"; // add title Font titleFont = new Font("Tahoma", 24, PdfFontStyle.Bold); Rect rcPage = PdfUtils.PageRectangle(pdf); Rect rc = PdfUtils.RenderParagraph(pdf, pdf.DocumentInfo.Title, titleFont, rcPage, rcPage, false); rc.Y += 12; // create nonsense document var bkmk = new List<string[]>(); Font headerFont = new Font("Arial", 14, PdfFontStyle.Bold); Font bodyFont = new Font("Times New Roman", 11); for (int i = 0; i < 30; i++) { // create ith header (as a link target and outline entry) string header = string.Format("{0}. {1}", i + 1, BuildRandomTitle()); rc = PdfUtils.RenderParagraph(pdf, header, headerFont, rcPage, rc, true, true); // save bookmark to build TOC later int pageNumber = pdf.CurrentPage + 1; bkmk.Add(new string[] { pageNumber.ToString(), header }); // create some text rc.X += 36; rc.Width -= 36; for (int j = 0; j < 3 + _rnd.Next(20); j++) { string text = BuildRandomParagraph(); rc = PdfUtils.RenderParagraph(pdf, text, bodyFont, rcPage, rc); rc.Y += 6; } rc.X -= 36; rc.Width += 36; rc.Y += 20; } // start Table of Contents pdf.NewPage(); // start TOC on a new page int tocPage = pdf.CurrentPage; // save page index (to move TOC later) rc = PdfUtils.RenderParagraph(pdf, "Table of Contents", titleFont, rcPage, rcPage, true); rc.Y += 12; rc.X += 30; rc.Width -= 40; // render Table of Contents Pen dottedPen = new Pen(Colors.Gray, 1.5f); dottedPen.DashStyle = DashStyle.Dot; StringFormat sfRight = new StringFormat(); sfRight.Alignment = HorizontalAlignment.Right; rc.Height = bodyFont.Size * 1.2; foreach (string[] entry in bkmk) { // get bookmark info string page = entry[0]; string header = entry[1]; // render header name and page number pdf.DrawString(header, bodyFont, Colors.Black, rc); pdf.DrawString(page, bodyFont, Colors.Black, rc, sfRight); #if true // connect the two with some dots (looks better than a dotted line) string dots = ". "; var wid = pdf.MeasureString(dots, bodyFont).Width; var x1 = rc.X + pdf.MeasureString(header, bodyFont).Width + 8; var x2 = rc.Right - pdf.MeasureString(page, bodyFont).Width - 8; var x = rc.X; for (rc.X = x1; rc.X < x2; rc.X += wid) { pdf.DrawString(dots, bodyFont, Colors.Gray, rc); } rc.X = x; #else // connect with a dotted line (another option) var x1 = rc.X + pdf.MeasureString(header, bodyFont).Width + 5; var x2 = rc.Right - pdf.MeasureString(page, bodyFont).Width - 5; var y = rc.Top + bodyFont.Size; pdf.DrawLine(dottedPen, x1, y, x2, y); #endif // add local hyperlink to entry pdf.AddLink("#" + header, rc); // move on to next entry rc = PdfUtils.Offset(rc, 0, rc.Height); if (rc.Bottom > rcPage.Bottom) { pdf.NewPage(); rc.Y = rcPage.Y; } } // move table of contents to start of document PdfPage[] arr = new PdfPage[pdf.Pages.Count - tocPage]; pdf.Pages.CopyTo(tocPage, arr, 0, arr.Length); pdf.Pages.RemoveRange(tocPage, arr.Length); pdf.Pages.InsertRange(0, arr); }
static void CreateDocumentGraphics(C1PdfDocument pdf) { // set up to draw Rect rc = new Rect(0, 0, 300, 200); string text = "Hello world of .NET Graphics and PDF.\r\nNice to meet you."; Font font = new Font("Times New Roman", 12, PdfFontStyle.Italic | PdfFontStyle.Underline); // draw to pdf document int penWidth = 0; byte penRGB = 0; pdf.FillPie(Colors.Red, rc, 0, 20f); pdf.FillPie(Colors.Green, rc, 20f, 30f); pdf.FillPie(Colors.Blue, rc, 60f, 12f); pdf.FillPie(Colors.Orange, rc, -80f, -20f); for (float startAngle = 0; startAngle < 360; startAngle += 40) { Color penColor = Color.FromArgb(0xff, penRGB, penRGB, penRGB); Pen pen = new Pen(penColor, penWidth++); penRGB = (byte)(penRGB + 20); pdf.DrawArc(pen, rc, startAngle, 40f); } pdf.DrawRectangle(Colors.Red, rc); pdf.DrawString(text, font, Colors.Black, rc); // show a Bezier curve var pts = new Point[] { new Point(400, 100), new Point(420, 30), new Point(500, 140), new Point(530, 20), }; // draw Bezier pdf.DrawBezier(new Pen(Colors.Blue, 4), pts[0], pts[1], pts[2], pts[3]); // show Bezier control points pdf.DrawLines(Colors.Gray, pts); foreach (Point pt in pts) { pdf.FillRectangle(Colors.Red, pt.X - 2, pt.Y - 2, 4, 4); } // title pdf.DrawString("Simple Bezier", font, Colors.Black, new Rect(500, 150, 100, 100)); }
static void CreateDocumentImages(C1PdfDocument pdf) { // calculate page rect (discounting margins) Rect rcPage = PdfUtils.PageRectangle(pdf); // load image into writeable bitmap BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = DataAccess.GetStream("borabora.jpg"); bi.EndInit(); var wb = new WriteableBitmap(bi); // center image on page preserving aspect ratio pdf.DrawImage(wb, rcPage, ContentAlignment.MiddleCenter, Stretch.Uniform); }
static void CreateDocumentPaperSizes(C1PdfDocument pdf) { // add title Font titleFont = new Font("Tahoma", 24, PdfFontStyle.Bold); Rect rc = PdfUtils.PageRectangle(pdf); PdfUtils.RenderParagraph(pdf, pdf.DocumentInfo.Title, titleFont, rc, rc, false); // create constant font and StringFormat objects Font font = new Font("Tahoma", 18); StringFormat sf = new StringFormat(); sf.Alignment = HorizontalAlignment.Center; sf.LineAlignment = VerticalAlignment.Center; // create one page with each paper size bool firstPage = true; foreach (var fi in typeof(PaperKind).GetFields(BindingFlags.Static | BindingFlags.Public)) { // Silverlight/Phone doesn't have Enum.GetValues PaperKind pk = (PaperKind)fi.GetValue(null); // skip custom size if (pk == PaperKind.Custom) continue; // add new page for every page after the first one if (!firstPage) pdf.NewPage(); firstPage = false; // set paper kind and orientation pdf.PaperKind = pk; pdf.Landscape = !pdf.Landscape; // draw some content on the page rc = PdfUtils.PageRectangle(pdf); rc = PdfUtils.Inflate(rc, -6, -6); string text = string.Format("PaperKind: [{0}];\r\nLandscape: [{1}];\r\nFont: [Tahoma 18pt]", pdf.PaperKind, pdf.Landscape); pdf.DrawString(text, font, Colors.Black, rc, sf); pdf.DrawRectangle(Colors.Black, rc); } }
static void CreateDocumentTextFlow(C1PdfDocument pdf) { // load long string from resource file string text = "Resource not found..."; using (var sr = new StreamReader(DataAccess.GetStream("flow.txt"))) { text = sr.ReadToEnd(); } text = text.Replace("\t", " "); text = string.Format("{0}\r\n\r\n---oOoOoOo---\r\n\r\n{0}", text); // create pdf document pdf.DocumentInfo.Title = "Text Flow"; // add title Font titleFont = new Font("Tahoma", 24, PdfFontStyle.Bold); Font bodyFont = new Font("Tahoma", 9); Rect rcPage = PdfUtils.PageRectangle(pdf); Rect rc = PdfUtils.RenderParagraph(pdf, pdf.DocumentInfo.Title, titleFont, rcPage, rcPage, false); rc.Y += titleFont.Size + 6; rc.Height = rcPage.Height - rc.Y; // create two columns for the text Rect rcLeft = rc; rcLeft.Width = rcPage.Width / 2 - 12; rcLeft.Height = 300; rcLeft.Y = (rcPage.Y + rcPage.Height - rcLeft.Height) / 2; Rect rcRight = rcLeft; rcRight.X = rcPage.Right - rcRight.Width; // start with left column rc = rcLeft; // render string spanning columns and pages for (; ; ) { // render as much as will fit into the rectangle rc = PdfUtils.Inflate(rc, -3, -3); int nextChar = pdf.DrawString(text, bodyFont, Colors.Black, rc); rc = PdfUtils.Inflate(rc, +3, +3); pdf.DrawRectangle(Colors.LightGray, rc); // break when done if (nextChar >= text.Length) { break; } // get rid of the part that was rendered text = text.Substring(nextChar); // switch to right-side rectangle if (rc.Left == rcLeft.Left) { rc = rcRight; } else // switch to left-side rectangle on the next page { pdf.NewPage(); rc = rcLeft; } } }
static Rect RenderTableHeader(C1PdfDocument pdf, Font font, Rect rc, string[] fields) { // calculate cell width (same for all columns) Rect rcCell = rc; rcCell.Width = rc.Width / fields.Length; rcCell.Height = 0; // calculate cell height (max of all columns) foreach (string field in fields) { var height = pdf.MeasureString(field, font, rcCell.Width).Height; rcCell.Height = Math.Max(rcCell.Height, height); } rcCell.Height += 6; // add 6 point margin // render header cells var fmt = new StringFormat(); fmt.LineAlignment = VerticalAlignment.Center; foreach (string field in fields) { pdf.FillRectangle(Colors.Black, rcCell); pdf.DrawString(field, font, Colors.White, rcCell, fmt); rcCell = PdfUtils.Offset(rcCell, rcCell.Width, 0); } // update rectangle and return it return PdfUtils.Offset(rc, 0, rcCell.Height); }
public static void RenderGrid(C1PdfDocument pdf, C1FlexGrid flex, PdfExportOptions options) { // get rendering options if (options == null) { options = new PdfExportOptions(); } // get root element to lay out the PDF pages Panel root = null; for (var parent = flex.Parent as FrameworkElement; parent != null; parent = parent.Parent as FrameworkElement) { if (parent is Panel) { root = parent as Panel; } } // get page size var rc = pdf.PageRectangle; // create panel to hold elements while they render var pageTemplate = new PageTemplate(); pageTemplate.Width = rc.Width; pageTemplate.Height = rc.Height; pageTemplate.SetPageMargin(options.Margin); root.Children.Add(pageTemplate); // render grid into PDF document var m = options.Margin; var sz = new Size(rc.Width - m.Left - m.Right, rc.Height - m.Top - m.Bottom); var pages = flex.GetPageImages(options.ScaleMode, sz, 100); for (int i = 0; i < pages.Count; i++) { // skip a page when necessary if (i > 0) { pdf.NewPage(); } // set content pageTemplate.PageContent.Child = pages[i]; pageTemplate.PageContent.Stretch = options.ScaleMode == ScaleMode.ActualSize ? System.Windows.Media.Stretch.None : System.Windows.Media.Stretch.Uniform; // set header/footer text pageTemplate.HeaderLeft.Text = options.DocumentTitle; if (options.KnownPageCount) { pageTemplate.FooterRight.Text = string.Format("Page {0} of {1}", pdf.CurrentPage + 1, pages.Count); } else { pageTemplate.FooterRight.Text = string.Format("Page {0}", pdf.CurrentPage + 1); } // measure page element pageTemplate.UpdateLayout(); pageTemplate.Arrange(new Rect(0, 0, rc.Width, rc.Height)); // add to PDF pdf.DrawElement(pageTemplate, rc); } // done with template root.Children.Remove(pageTemplate); }
public static void RenderGrid(C1PdfDocument pdf, C1FlexGrid flex) { RenderGrid(pdf, flex, null); }
void CreateDocumentVisualTree(C1PdfDocument pdf, FrameworkElement targetElement) { // set up to render var font = new Font("Courier", 14); var img = new WriteableBitmap(CreateBitmap(targetElement)); // go render bool firstPage = true; foreach (Stretch stretch in new Stretch[] { Stretch.Fill, Stretch.None, Stretch.Uniform, Stretch.UniformToFill }) { // add page break if (!firstPage) { pdf.NewPage(); } firstPage = false; // set up to render var alignment = ContentAlignment.TopLeft; var rc = PdfUtils.Inflate(pdf.PageRectangle, -72, -72); rc.Height /= 2; // render element as image pdf.DrawString("Element as Image, Stretch: " + stretch.ToString(), font, Colors.Black, rc); rc = PdfUtils.Inflate(rc, -20, -20); pdf.DrawImage(img, rc, alignment, stretch); pdf.DrawRectangle(Colors.Green, rc); rc = PdfUtils.Inflate(rc, +20, +20); pdf.DrawRectangle(Colors.Green, rc); // move to bottom of the page rc = PdfUtils.Offset(rc, 0, rc.Height + 20); // render element pdf.DrawString("Element as VisualTree, Stretch: " + stretch.ToString(), font, Colors.Black, rc); rc = PdfUtils.Inflate(rc, -20, -20); pdf.DrawElement(targetElement, rc, alignment, stretch); pdf.DrawRectangle(Colors.Green, rc); rc = PdfUtils.Inflate(rc, +20, +20); pdf.DrawRectangle(Colors.Green, rc); } }
static Rect RenderTable(C1PdfDocument pdf, Rect rc, Rect rcPage, DataTable table, string[] fields) { // select fonts Font hdrFont = new Font("Tahoma", 10, PdfFontStyle.Bold); Font txtFont = new Font("Tahoma", 8); // build table pdf.AddBookmark(table.TableName, 0, rc.Y); rc = PdfUtils.RenderParagraph(pdf, "NorthWind " + table.TableName, hdrFont, rcPage, rc, false); // build table rc = RenderTableHeader(pdf, hdrFont, rc, fields); foreach (DataRow dr in table.Rows) { rc = RenderTableRow(pdf, txtFont, hdrFont, rcPage, rc, fields, dr); } // done return rc; }
static void CreateDocumentTables(C1PdfDocument pdf) { // get the data var ds = DataAccess.GetDataSet(); // calculate page rect (discounting margins) Rect rcPage = PdfUtils.PageRectangle(pdf); Rect rc = rcPage; // add title Font titleFont = new Font("Tahoma", 24, PdfFontStyle.Bold); rc = PdfUtils.RenderParagraph(pdf, pdf.DocumentInfo.Title, titleFont, rcPage, rc, false); // render some tables RenderTable(pdf, rc, rcPage, ds.Tables["Customers"], new string[] { "CompanyName", "ContactName", "Country", "Address", "Phone" }); pdf.NewPage(); rc = rcPage; RenderTable(pdf, rc, rcPage, ds.Tables["Products"], new string[] { "ProductName", "QuantityPerUnit", "UnitPrice", "UnitsInStock", "UnitsOnOrder" }); pdf.NewPage(); rc = rcPage; RenderTable(pdf, rc, rcPage, ds.Tables["Employees"], new string[] { "FirstName", "LastName", "Country", "Notes" }); }
static Rect RenderTableRow(C1PdfDocument pdf, Font font, Font hdrFont, Rect rcPage, Rect rc, string[] fields, DataRow dr) { // calculate cell width (same for all columns) Rect rcCell = rc; rcCell.Width = rc.Width / fields.Length; rcCell.Height = 0; // calculate cell height (max of all columns) rcCell = PdfUtils.Inflate(rcCell, -4, 0); foreach (string field in fields) { string text = dr[field].ToString(); var height = pdf.MeasureString(text, font, rcCell.Width).Height; rcCell.Height = Math.Max(rcCell.Height, height); } rcCell = PdfUtils.Inflate(rcCell, 4, 0); // add 4 point margin rcCell.Height += 2; // break page if we have to if (rcCell.Bottom > rcPage.Bottom) { pdf.NewPage(); rc = RenderTableHeader(pdf, hdrFont, rcPage, fields); rcCell.Y = rc.Y; } // center vertically just to show how StringFormat fmt = new StringFormat(); fmt.LineAlignment = VerticalAlignment.Center; // render data cells foreach (string field in fields) { // get content string text = dr[field].ToString(); // set horizontal alignment double d; fmt.Alignment = (double.TryParse(text, NumberStyles.Any, CultureInfo.CurrentCulture, out d)) ? HorizontalAlignment.Right : HorizontalAlignment.Left; // render cell pdf.DrawRectangle(Colors.LightGray, rcCell); rcCell = PdfUtils.Inflate(rcCell, -4, 0); pdf.DrawString(text, font, Colors.Black, rcCell, fmt); rcCell = PdfUtils.Inflate(rcCell, 4, 0); rcCell = PdfUtils.Offset(rcCell, rcCell.Width, 0); } // update rectangle and return it return PdfUtils.Offset(rc, 0, rcCell.Height); }
public static void HandleButtonClick(object sender, RoutedEventArgs e) { // get stream to save to var dlg = new SaveFileDialog(); dlg.DefaultExt = ".pdf"; var dr = dlg.ShowDialog(); if (!dr.HasValue || !dr.Value) { return; } // get sender button var btn = sender as Button; // create document var pdf = new C1PdfDocument(PaperKind.Letter); pdf.Clear(); // set document info var di = pdf.DocumentInfo; di.Author = "ComponentOne"; di.Subject = "C1.WPF.Pdf demo."; di.Title = (string)btn.Content; //// add some security //if (false) //{ // var si = pdf.Security; // si.AllowPrint = false; // si.AllowEditAnnotations = false; // si.AllowEditContent = false; // si.AllowCopyContent = false; // //si.UserPassword = "******"; // //si.OwnerPassword = "******"; //} //// set viewer preferences //if (false) //{ // var vp = pdf.ViewerPreferences; // vp.CenterWindow = true; // vp.FitWindow = true; // vp.PageLayout = PageLayout.TwoColumnLeft; // vp.PageMode = PageMode.FullScreen; //} // create document switch (di.Title) { case "Quotes": CreateDocumentQuotes(pdf); break; case "Tables": CreateDocumentTables(pdf); break; case "Images": CreateDocumentImages(pdf); break; case "Paper Sizes": CreateDocumentPaperSizes(pdf); break; case "Table of Contents": CreateDocumentTOC(pdf); break; case "Text Flow": CreateDocumentTextFlow(pdf); break; case "Text": CreateDocumentText(pdf); break; case "Graphics": CreateDocumentGraphics(pdf); break; } // render footers // this reopens each page and adds content to them (now we know the page count). var font = new Font("Arial", 8, PdfFontStyle.Bold); var fmt = new StringFormat(); fmt.Alignment = HorizontalAlignment.Right; fmt.LineAlignment = VerticalAlignment.Bottom; for (int page = 0; page < pdf.Pages.Count; page++) { pdf.CurrentPage = page; var text = string.Format("C1.WPF.Pdf: {0}, page {1} of {2}", di.Title, page + 1, pdf.Pages.Count); pdf.DrawString( text, font, Colors.DarkGray, PdfUtils.Inflate(pdf.PageRectangle, -72, -36), fmt); } // save document using (var stream = dlg.OpenFile()) { pdf.Save(stream); } MessageBox.Show("Pdf Document saved to " + dlg.SafeFileName); }