public static PdfDocument CombinePdfPng(string pdfIn, string id, IHostingEnvironment _hostingEnvironment) { /* Get paths of documents to combine */ string nCodedPdf = pdfIn; //string templateDocument = "NDAExample.pdf"; // todo: string templateDocument = pdfIn; string pngImage = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "img/pen/" + id + ".png"); // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show consecutive pages facing //outputDocument.PageLayout = PdfPageLayout.TwoPageLeft; XGraphics gfx; //XRect box; // Open the external documents as XPdfForm objects. Such objects are // treated like images. By default the first page of the document is // referenced by a new XPdfForm. using (var client = new WebClient()) { client.DownloadFile(pdfIn, System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "pdf/input.pdf")); } //switched the order - ncode must be written first, document written on top //XPdfForm formNcode = XPdfForm.FromFile(fs);//ncode XPdfForm formNcode = XPdfForm.FromFile("input.pdf");//ncode //XPdfForm formPngImage = XPdfForm.FromFile(pngImage); Console.WriteLine("formNcode.PixelHeight: " + formNcode.PixelHeight); Console.WriteLine("formNcode.PixelWidth: " + formNcode.PixelWidth); //int count = formTemplate.PageCount; gfx = XGraphics.FromPdfPage(outputDocument.AddPage()); gfx.DrawImage(formNcode, new XRect(0, 0, 595, 842)); using (XImage sig = XImage.FromFile(pngImage)) { gfx.DrawImage(sig, new XRect(0, 0, 595, 842)); } //gfx = XGraphics.FromPdfPage(page1); gfx.Dispose(); outputDocument.Save(System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "pdf/ImageCombine.pdf")); outputDocument.Dispose(); return(outputDocument); }
/// <summary> /// Append PDF and bitmap image to result PDF file. /// </summary> public void AppendToResultPdf() { string resultFileName = Path.Combine(OutputDirectory, "~TestResult.pdf"); PdfDocument pdfResultDocument = null; if (File.Exists(resultFileName)) { pdfResultDocument = PdfReader.Open(resultFileName, PdfDocumentOpenMode.Modify); } else { pdfResultDocument = new PdfDocument(); pdfResultDocument.Info.Title = "XPS to PDF Unit Tests"; pdfResultDocument.Info.Author = "Stefan Lange"; pdfResultDocument.PageLayout = PdfPageLayout.SinglePage; pdfResultDocument.PageMode = PdfPageMode.UseNone; pdfResultDocument.ViewerPreferences.FitWindow = true; pdfResultDocument.ViewerPreferences.CenterWindow = true; } PdfPage page = pdfResultDocument.AddPage(); page.Orientation = PageOrientation.Landscape; XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawRectangle(XBrushes.GhostWhite, new XRect(0, 0, 1000, 1000)); double x1 = XUnit.FromMillimeter((297 - 2 * WidthInMillimeter) / 3); double x2 = XUnit.FromMillimeter((297 - 2 * WidthInMillimeter) / 3 * 2 + WidthInMillimeter); double y = XUnit.FromMillimeter((210 - HeightInMillimeter) / 2); double yt = XUnit.FromMillimeter(HeightInMillimeter) + y + 20; gfx.DrawString(String.Format("XPS to PDF Unit Test '{0}'", this.Name), new XFont("Arial", 9, XFontStyle.Bold), XBrushes.DarkRed, new XPoint(x1, 30)); // Draw the PDF result gfx.DrawString("This is a vector based PDF form created with PDFsharp from an XPS file", new XFont("Arial", 8), XBrushes.DarkBlue, new XRect(x1, yt, WidthInPoint, 0), XStringFormats.Default); XPdfForm form = XPdfForm.FromFile(Path.Combine(OutputDirectory, Name + ".pdf")); gfx.DrawImage(form, new XPoint(x1, y)); // Draw the result bitmap gfx.DrawString("As a reference, this is a bitmap image created with WPF from the Visual contained in the XPS file", new XFont("Arial", 8), XBrushes.DarkBlue, new XRect(x2, yt, WidthInPoint, 0), XStringFormats.Default); XImage image = XImage.FromFile(Path.Combine(OutputDirectory, Name + ".png")); image.Interpolate = false; gfx.DrawImage(image, new XPoint(x2, y)); pdfResultDocument.Save(resultFileName); }
/// <summary> /// Übernimmt das Kominieren von je zwei A5 Seiten zu einer A4 Seite und das Skalieren, je nach gewähltem Modus (scale). /// </summary> private void _CombineAndScale(string outputPdfPath, bool scale) { XPdfForm form = XPdfForm.FromFile(_tmpPath); XGraphics gfx; XRect rect; PdfPage page; PageFormat pf; PdfDocument outputDocument = new PdfDocument(); for (int i = 0; i < form.PageCount; i++) { page = outputDocument.Pages.Add(); page.Size = PageSize.A4; form.PageNumber = i + 1; gfx = XGraphics.FromPdfPage(page); if (!scale) { pf = _GetPageFormat(form.PointWidth, form.PointHeight); if (pf == PageFormat.A5Landscape) { rect = new XRect(0, 0, _A4Size.Width, _A4Size.Height / 2); gfx.DrawImage(form, rect); if (i + 1 < form.PageCount) { form.PageNumber = i + 2; pf = _GetPageFormat(form.PointWidth, form.PointHeight); if (pf == PageFormat.A5Landscape) { rect = new XRect(0, _A4Size.Height / 2, _A4Size.Width, _A4Size.Height / 2); gfx.DrawImage(form, rect); i++; } } continue; } } rect = new XRect(0, 0, _A4Size.Width, _A4Size.Height); gfx.DrawImage(form, rect); } outputDocument.Save(outputPdfPath); }
/// <summary> /// from http://forum.pdfsharp.net/viewtopic.php?p=2069 /// Get a version of the document which pdfsharp can open, downgrading if necessary /// </summary> static private XPdfForm OpenDocumentForPdfSharp(string path) { try { var form = XPdfForm.FromFile(path); //this causes it to notice if can't actually read it int dummy = form.PixelWidth; return(form); } catch (PdfSharp.Pdf.IO.PdfReaderException) { //workaround if pdfsharp doesnt dupport this pdf return(XPdfForm.FromFile(WritePdf1pt4Version(path))); } }
// This is a subset of what MakeBooklet normally does, just enough to make it process the PDF to the // point where an exception will be thrown if the file is corrupt as in BL-932. // Possibly one day we will find a faster or more comprehensive way of validating a PDF, but this // at least catches the problem we know about. private static void CheckPdf(string outputPdfPath) { var pdf = XPdfForm.FromFile(outputPdfPath); PdfDocument outputDocument = new PdfDocument(); outputDocument.PageLayout = PdfPageLayout.SinglePage; var page = outputDocument.AddPage(); using (XGraphics gfx = XGraphics.FromPdfPage(page)) { XRect sourceRect = new XRect(0, 0, pdf.PixelWidth, pdf.PixelHeight); // We don't really care about drawing the image of the page here, just forcing the // reader to process the PDF file enough to crash if it is corrupt. gfx.DrawImage(pdf, sourceRect); } }
public static void DrawBeziers() { string fn = @"input.pdf"; using (PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(fn)) { // Create an empty XForm object with the specified width and height // A form is bound to its target document when it is created. The reason is that the form can // share fonts and other objects with its target document. using (XForm form = new XForm(document, XUnit.FromMillimeter(70), XUnit.FromMillimeter(55))) { // Create an XGraphics object for drawing the contents of the form. using (XGraphics formGfx = XGraphics.FromForm(form)) { // Draw a large transparent rectangle to visualize the area the form occupies XColor back = XColors.Orange; back.A = 0.2; XSolidBrush brush = new XSolidBrush(back); formGfx.DrawRectangle(brush, -10000, -10000, 20000, 20000); // On a form you can draw... // ... text formGfx.DrawString("Text, Graphics, Images, and Forms", new XFont("Verdana", 10, XFontStyle.Regular), XBrushes.Navy, 3, 0, XStringFormats.TopLeft); XPen pen = XPens.LightBlue.Clone(); pen.Width = 2.5; // ... graphics like Bézier curves formGfx.DrawBeziers(pen, XPoint.ParsePoints("30,120 80,20 100,140 175,33.3")); // ... raster images like GIF files XGraphicsState state = formGfx.Save(); formGfx.RotateAtTransform(17, new XPoint(30, 30)); formGfx.DrawImage(XImage.FromFile("../../../../../../dev/XGraphicsLab/images/Test.gif"), 20, 20); formGfx.Restore(state); // ... and forms like XPdfForm objects state = formGfx.Save(); formGfx.RotateAtTransform(-8, new XPoint(165, 115)); formGfx.DrawImage(XPdfForm.FromFile("../../../../../PDFs/SomeLayout.pdf"), new XRect(140, 80, 50, 50 * System.Math.Sqrt(2))); formGfx.Restore(state); // When you finished drawing on the form, dispose the XGraphic object. } // End Using formGfx } // End Using form } // End Using document }
private void Button_Click_1(object sender, RoutedEventArgs e) { //if(newLabelPosition.Y <= 0) newLabelPosition.Y = DiplomaBackground.Margin.Top + DiplomaBackground.Height - ParticipantNameLabel.ActualHeight; //double posY = (newLabelPosition.Y + (ParticipantNameLabel.ActualHeight / 2) - DiplomaBackground.Margin.Top) / DiplomaBackground.Height; //double posX = (newLabelPosition.X - DiplomaBackground.Margin.Left) / DiplomaBackground.Width; double posY = (ParticipantNameLabel.Margin.Top + (ParticipantNameLabel.ActualHeight / 2) - DiplomaBackground.Margin.Top) / DiplomaBackground.Height; Globals.database.selectFromDatabase(); while (Globals.database.rdr.Read()) { string firstName = Globals.database.rdr.GetString(0); string lastName = Globals.database.rdr.GetString(1); string email = Globals.database.rdr.GetString(2); PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics graph = XGraphics.FromPdfPage(page); document.Options.NoCompression = true; document.Options.ColorMode = PdfColorMode.Cmyk; document.Version = 14; page.Size = PdfSharp.PageSize.A4; XPdfForm pageFromExternalFile = XPdfForm.FromFile(pathToBackground); graph.DrawImage(pageFromExternalFile, new XRect(0, 0, pageFromExternalFile.PointWidth, pageFromExternalFile.PointHeight)); // dodanie tekstu w PDFie XFont font = new XFont("Roboto Condensed Light", 40, XFontStyle.Bold); graph.DrawString(firstName + " " + lastName, font, XBrushes.Black, page.Width.Point / 2, page.Height.Point * posY, XStringFormats.Center); string fileName = pathToGeneratedPDF + "\\" + firstName + lastName + ".pdf"; document.Save(fileName); } Globals.database.rdr.Close(); }
public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument) { if (String.IsNullOrEmpty(xpsFilename)) { throw new ArgumentNullException("xpsFilename"); } if (String.IsNullOrEmpty(pdfFilename)) { pdfFilename = xpsFilename; if (IOPath.HasExtension(pdfFilename)) { pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.')); } pdfFilename += ".pdf"; } using (var xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read)) { Convert(xpsDocument, pdfFilename, docIndex); } if (!createComparisonDocument) { return; } try { using (var xpsDoc = new XpsDocument(xpsFilename, FileAccess.Read)) { var docSeq = xpsDoc.GetFixedDocumentSequence(); if (docSeq == null) { throw new InvalidOperationException("docSeq"); } XPdfForm form = XPdfForm.FromFile(pdfFilename); PdfDocument pdfComparisonDocument = new PdfDocument(); var pageIndex = 0; var refs = docSeq.References; var docs = refs.Select(r => r.GetDocument(false)); foreach (var doc in docs) { foreach (var page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = pdfComparisonDocument.AddPage(); double width = page.Width; double height = page.Height; pdfPage.Width = page.Width * 2; pdfPage.Height = page.Height; DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex); //byte[] png = PngFromPage(docPage, 96); BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2); XImage image = XImage.FromBitmapSource(bmsource); XGraphics gfx = XGraphics.FromPdfPage(pdfPage); form.PageIndex = pageIndex; gfx.DrawImage(form, 0, 0, width, height); gfx.DrawImage(image, width, 0, width, height); //renderer.RenderPage(pdfPage, page); pageIndex++; } } string pdfComparisonFilename = pdfFilename; if (IOPath.HasExtension(pdfComparisonFilename)) { pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.')); } pdfComparisonFilename += "-comparison.pdf"; pdfComparisonDocument.ViewerPreferences.FitWindow = true; //pdfComparisonDocument.PageMode = PdfPageMode. pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage; pdfComparisonDocument.Save(pdfComparisonFilename); } } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
/// <summary> /// /// </summary> /// <param name="pdfPath">this is the path where it already exists, and the path where we leave the transformed version</param> /// <param name="incomingPaperSize"></param> /// <param name="booketLayoutMethod"></param> /// <param name="layoutPagesForRightToLeft"></param> private void MakeBooklet(string pdfPath, string incomingPaperSize, PublishModel.BookletLayoutMethod booketLayoutMethod, bool layoutPagesForRightToLeft) { //TODO: we need to let the user chose the paper size, as they do in PdfDroplet. //For now, just assume a size double the original PageSize pageSize; switch (incomingPaperSize) { case "A3": pageSize = PageSize.A2; break; case "A4": pageSize = PageSize.A3; break; case "A5": pageSize = PageSize.A4; break; case "A6": pageSize = PageSize.A5; break; case "B5": pageSize = PageSize.B4; break; case "Letter": pageSize = PageSize.Ledger; break; case "HalfLetter": pageSize = PageSize.Letter; break; case "QuarterLetter": pageSize = PageSize.Statement; // ?? Wikipedia says HalfLetter is aka Statement break; case "Legal": pageSize = PageSize.Legal; //TODO... what's reasonable? break; case "HalfLegal": pageSize = PageSize.Legal; break; default: throw new ApplicationException("PdfMaker.MakeBooklet() does not contain a map from " + incomingPaperSize + " to a PdfSharp paper size."); } using (var incoming = new TempFile()) { RobustFile.Delete(incoming.Path); RobustFile.Move(pdfPath, incoming.Path); LayoutMethod method; switch (booketLayoutMethod) { case PublishModel.BookletLayoutMethod.NoBooklet: method = new NullLayoutMethod(); break; case PublishModel.BookletLayoutMethod.SideFold: // To keep the GUI simple, we assume that A6 page size for booklets // implies 4up printing on A4 paper. This feature was requested by // https://jira.sil.org/browse/BL-1059 "A6 booklets should print 4 // to an A4 sheet". The same is done for QuarterLetter booklets // printing on Letter size sheets. if (incomingPaperSize == "A6") { method = new SideFold4UpBookletLayouter(); pageSize = PageSize.A4; } else if (incomingPaperSize == "QuarterLetter") { method = new SideFold4UpBookletLayouter(); pageSize = PageSize.Letter; } else { method = new SideFoldBookletLayouter(); } break; case PublishModel.BookletLayoutMethod.CutAndStack: method = new CutLandscapeLayout(); break; case PublishModel.BookletLayoutMethod.Calendar: method = new CalendarLayouter(); break; default: throw new ArgumentOutOfRangeException("booketLayoutMethod"); } var paperTarget = new PaperTarget("ZZ" /*we're not displaying this anyhwere, so we don't need to know the name*/, pageSize); var pdf = XPdfForm.FromFile(incoming.Path); //REVIEW: this whole giving them the pdf and the file too... I checked once and it wasn't wasting effort...the path was only used with a NullLayout option method.Layout(pdf, incoming.Path, pdfPath, paperTarget, layoutPagesForRightToLeft, ShowCropMarks); } }
/// <summary> /// Imports the pages as form X objects. /// Note that this technique copies only the visual content and the /// hyperlinks do not work. /// </summary> static void Variant2() { // Get fresh copies of the sample PDF files const string filename1 = "Portable Document Format.pdf"; File.Copy(Path.Combine("../../../../../PDFs/", filename1), Path.Combine(Directory.GetCurrentDirectory(), filename1), true); const string filename2 = "Portable Document Format.pdf"; File.Copy(Path.Combine("../../../../../PDFs/", filename2), Path.Combine(Directory.GetCurrentDirectory(), filename2), true); // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show consecutive pages facing outputDocument.PageLayout = PdfPageLayout.TwoPageLeft; XFont font = new XFont("Verdana", 10, XFontStyle.Bold); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; XGraphics gfx; XRect box; // Open the external documents as XPdfForm objects. Such objects are // treated like images. By default the first page of the document is // referenced by a new XPdfForm. XPdfForm form1 = XPdfForm.FromFile(filename1); XPdfForm form2 = XPdfForm.FromFile(filename2); int count = Math.Max(form1.PageCount, form2.PageCount); for (int idx = 0; idx < count; idx++) { // Add two new pages to the output document PdfPage page1 = outputDocument.AddPage(); PdfPage page2 = outputDocument.AddPage(); if (form1.PageCount > idx) { // Get a graphics object for page1 gfx = XGraphics.FromPdfPage(page1); // Set page number (which is one-based) form1.PageNumber = idx + 1; // Draw the page identified by the page number like an image gfx.DrawImage(form1, new XRect(0, 0, form1.PointWidth, form1.PointHeight)); // Write document file name and page number on each page box = page1.MediaBox.ToXRect(); box.Inflate(0, -10); gfx.DrawString(String.Format("{0} • {1}", filename1, idx + 1), font, XBrushes.Red, box, format); } // Same as above for second page if (form2.PageCount > idx) { gfx = XGraphics.FromPdfPage(page2); form2.PageNumber = idx + 1; gfx.DrawImage(form2, new XRect(0, 0, form2.PointWidth, form2.PointHeight)); box = page2.MediaBox.ToXRect(); box.Inflate(0, -10); gfx.DrawString(String.Format("{0} • {1}", filename2, idx + 1), font, XBrushes.Red, box, format); } } // Save the document... const string filename = "CompareDocument2_tempfile.pdf"; outputDocument.Save(filename); // ...and start a viewer. Process.Start(filename); }
static void Main() { // Get a fresh copy of the sample PDF file string filename = "Portable Document Format.pdf"; File.Copy(Path.Combine("../../../../../PDFs/", filename), Path.Combine(Directory.GetCurrentDirectory(), filename), true); // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show single pages // (Note: one page contains two pages from the source document. // If the number of pages of the source document can not be // divided by 4, the first pages of the output document will // each contain only one page from the source document.) outputDocument.PageLayout = PdfPageLayout.SinglePage; XGraphics gfx; // Open the external document as XPdfForm object XPdfForm form = XPdfForm.FromFile(filename); // Determine width and height double extWidth = form.PixelWidth; double extHeight = form.PixelHeight; int inputPages = form.PageCount; int sheets = inputPages / 4; if (sheets * 4 < inputPages) { sheets += 1; } int allpages = 4 * sheets; int vacats = allpages - inputPages; for (int idx = 1; idx <= sheets; idx += 1) { // Front page of a sheet: // Add a new page to the output document PdfPage page = outputDocument.AddPage(); page.Orientation = PageOrientation.Landscape; page.Width = 2 * extWidth; page.Height = extHeight; double width = page.Width; double height = page.Height; gfx = XGraphics.FromPdfPage(page); // Skip if left side has to remain blank XRect box; if (vacats > 0) { vacats -= 1; } else { // Set page number (which is one-based) for left side form.PageNumber = allpages + 2 * (1 - idx); box = new XRect(0, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); } // Set page number (which is one-based) for right side form.PageNumber = 2 * idx - 1; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Back page of a sheet page = outputDocument.AddPage(); page.Orientation = PageOrientation.Landscape; page.Width = 2 * extWidth; page.Height = extHeight; gfx = XGraphics.FromPdfPage(page); // Set page number (which is one-based) for left side form.PageNumber = 2 * idx; box = new XRect(0, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Skip if right side has to remain blank if (vacats > 0) { vacats -= 1; } else { // Set page number (which is one-based) for right side form.PageNumber = allpages + 1 - 2 * idx; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); } } // Save the document... filename = "Booklet.pdf"; outputDocument.Save(filename); // ...and start a viewer. Process.Start(filename); }
public static string CombinePdfPdf(Stream pdfIn, IHostingEnvironment _hostingEnvironment) { /* Get paths of documents to combine */ string nCodePaper = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "pdf/Neosmartpen_A4_A_Type_plain_en.pdf"); //string templateDocument = "NDAExample.pdf"; // todo: string templateDocument = pdfIn; XPdfForm formTemplate = XPdfForm.FromStream(pdfIn); // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show consecutive pages facing //outputDocument.PageLayout = PdfPageLayout.TwoPageLeft; XGraphics gfx; //XRect box; // Open the external documents as XPdfForm objects. Such objects are // treated like images. By default the first page of the document is // referenced by a new XPdfForm. //switched the order - ncode must be written first, document written on top XPdfForm formNcode = XPdfForm.FromFile(nCodePaper);//ncode Console.WriteLine("formNcode.PixelHeight: " + formNcode.PixelHeight); Console.WriteLine("formNcode.PixelWidth: " + formNcode.PixelWidth); int count = formTemplate.PageCount; for (int idx = 0; idx < count; idx++) { // Add a new page to the output document PdfPage page1 = outputDocument.AddPage(); // Get a graphics object for page1 gfx = XGraphics.FromPdfPage(page1); // draw the ncode page to the output document if (formNcode.PageCount > idx) { // Set page number (which is one-based) the first useable page from the ncode paper is page2 formNcode.PageNumber = idx + 2; // Draw the page identified by the page number like an image gfx.DrawImage(formNcode, new XRect(0, 0, 595, 842)); } // Same as above for second page if (formTemplate.PageCount > idx) { formTemplate.PageNumber = idx + 1; gfx.DrawImage(formTemplate, new XRect(0, 0, 595, 842)); } } // Save the document... string savePath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "pdf/outputFile.pdf"); outputDocument.Save(savePath); outputDocument.Dispose(); return(savePath); }
/// <summary> /// /// </summary> /// <param name="pdfPath">this is the path where it already exists, and the path where we leave the transformed version</param> /// <param name="incomingPaperSize"></param> /// <param name="booketLayoutMethod"></param> private void MakeBooklet(string pdfPath, string incomingPaperSize, PublishModel.BookletLayoutMethod booketLayoutMethod) { //TODO: we need to let the user chose the paper size, as they do in PdfDroplet. //For now, just assume a size double the original PageSize pageSize; switch (incomingPaperSize) { case "A3": pageSize = PageSize.A2; break; case "A4": pageSize = PageSize.A3; break; case "A5": pageSize = PageSize.A4; break; case "A6": pageSize = PageSize.A5; break; case "B5": pageSize = PageSize.B4; break; case "Letter": pageSize = PageSize.Letter; //TODO... what's reasonable? break; case "HalfLetter": pageSize = PageSize.Letter; break; case "Legal": pageSize = PageSize.Legal; //TODO... what's reasonable? break; default: throw new ApplicationException("PdfMaker.MakeBooklet() does not contain a map from " + incomingPaperSize + " to a PdfSharp paper size."); } using (var incoming = new TempFile()) { File.Delete(incoming.Path); File.Move(pdfPath, incoming.Path); LayoutMethod method; switch (booketLayoutMethod) { case PublishModel.BookletLayoutMethod.NoBooklet: method = new NullLayoutMethod(); break; case PublishModel.BookletLayoutMethod.SideFold: method = new SideFoldBookletLayouter(); break; case PublishModel.BookletLayoutMethod.CutAndStack: method = new CutLandscapeLayout(); break; case PublishModel.BookletLayoutMethod.Calendar: method = new CalendarLayouter(); break; default: throw new ArgumentOutOfRangeException("booketLayoutMethod"); } var paperTarget = new PaperTarget("ZZ" /*we're not displaying this anyhwere, so we don't need to know the name*/, pageSize); var pdf = XPdfForm.FromFile(incoming.Path); //REVIEW: this whole giving them the pdf and the file too... I checked once and it wasn't wasting effort...the path was only used with a NullLayout option method.Layout(pdf, incoming.Path, pdfPath, paperTarget, /*TODO: rightToLeft*/ false, ShowCropMarks); } }
static void Main() { // Get a fresh copy of the sample PDF file. var filename = "Portable Document Format.pdf"; var file = Path.Combine(Directory.GetCurrentDirectory(), filename); File.Copy(Path.Combine("../../../../assets/PDFs/", filename), file, true); // Remove ReadOnly attribute from the copy. File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly); // Create the output document. var outputDocument = new PdfDocument(); // Show single pages. // (Note: one page contains two pages from the source document) outputDocument.PageLayout = PdfPageLayout.SinglePage; var font = new XFont("Verdana", 8, XFontStyle.Bold); var format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; // Open the external document as XPdfForm object. var form = XPdfForm.FromFile(filename); for (var idx = 0; idx < form.PageCount; idx += 2) { // Add a new page to the output document. var page = outputDocument.AddPage(); page.Orientation = PageOrientation.Landscape; double width = page.Width; double height = page.Height; var gfx = XGraphics.FromPdfPage(page); // Set the page number (which is one-based). form.PageNumber = idx + 1; var box = new XRect(0, 0, width / 2, height); // Draw the page identified by the page number like an image. gfx.DrawImage(form, box); // Write page number on each page. box.Inflate(0, -10); gfx.DrawString(String.Format("- {0} -", idx + 1), font, XBrushes.Red, box, format); if (idx + 1 >= form.PageCount) { continue; } // Set the page number (which is one-based). form.PageNumber = idx + 2; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image. gfx.DrawImage(form, box); // Write page number on each page. box.Inflate(0, -10); gfx.DrawString(String.Format("- {0} -", idx + 2), font, XBrushes.Red, box, format); } // Save the document... filename = "TwoPagesOnOne_tempfile.pdf"; outputDocument.Save(filename); // ...and start a viewer. Process.Start(filename); }
private void PrintAsPDFAfterTilesAreLoaded() { AxMap.TilesLoaded -= AxMap_TilesLoaded; string localdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ResTBDesktop"; string localappdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\ResTBDesktop"; PdfDocument mapTemplate = PdfReader.Open(localappdata + "\\PrintTemplates\\A4_landscape.pdf", PdfDocumentOpenMode.Modify); PdfDocument outputDocument = new PdfDocument(); outputDocument.PageLayout = mapTemplate.PageLayout; PdfPage page = outputDocument.AddPage(); page.Orientation = mapTemplate.Pages[0].Orientation; page.Width = mapTemplate.Pages[0].Width; page.Height = mapTemplate.Pages[0].Height; int dx = (int)page.Width.Point, dy = (int)page.Height.Point; // calculate aspect var diffX = AxMap.Extents.xMax - AxMap.Extents.xMin; double aspect = ((double)dy / dx); int diffY = (int)(aspect * diffX); // start tile loading for cache Extents MapExtents = new Extents(); MapExtents.SetBounds(AxMap.Extents.xMin, AxMap.Extents.yMin, AxMap.Extents.zMin, AxMap.Extents.xMax, AxMap.Extents.yMin + diffY, AxMap.Extents.zMax); // scale double meter = AxMap.GeodesicDistance(AxMap.Extents.xMin, AxMap.Extents.yMin, AxMap.Extents.xMax, AxMap.Extents.yMin); double pageWidthInMeter = ((page.Width / 72) * 2.54) / 100; int scale = (int)(meter / pageWidthInMeter); int scaleRounded = scale % 100 >= 50 ? scale + 100 - scale % 100 : scale - scale % 100; if ((scale - scaleRounded < 10) && (scale - scaleRounded > -10)) { scale = scaleRounded; } // Load the template stuff and change the acroforms... PdfAcroForm acroform = mapTemplate.AcroForm; if (acroform.Elements.ContainsKey("/NeedAppearances")) { acroform.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true); } else { acroform.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true)); } var name = (PdfTextField)(acroform.Fields["ProjectTitle"]); changeFont(name, 12); name.Value = new PdfString(project.Name); var numberlabel = (PdfTextField)(acroform.Fields["ProjectNumberLabel"]); changeFont(numberlabel, 7); numberlabel.Value = new PdfString(Resources.Project_Number); var number = (PdfTextField)(acroform.Fields["ProjectNumber"]); changeFont(number, 7); number.Value = new PdfString(project.Number); var descriptionlabel = (PdfTextField)(acroform.Fields["DescriptionLabel"]); changeFont(descriptionlabel, 7); descriptionlabel.Value = new PdfString(Resources.Description); var description = (PdfTextField)(acroform.Fields["Description"]); changeFont(description, 7); description.Value = new PdfString(project.Description); var scalefield = (PdfTextField)(acroform.Fields["Scale"]); changeFont(scalefield, 10); scalefield.Value = new PdfString("1 : " + (int)scale); var legend = (PdfTextField)(acroform.Fields["LegendLabel"]); legend.Value = new PdfString(Resources.Legend); var copyright = (PdfTextField)(acroform.Fields["CopyrightLabel"]); copyright.Value = new PdfString("Impreso con " + Resources.App_Name); mapTemplate.Flatten(); mapTemplate.Save(localdata + "\\printtemp.pdf"); mapTemplate.Close(); XGraphics gfx = XGraphics.FromPdfPage(page); var imageFromMap = AxMap.SnapShot3(AxMap.Extents.xMin, AxMap.Extents.xMax, AxMap.Extents.yMin + diffY, AxMap.Extents.yMin, (int)(dx * (96.0 / 72.0) * 2)); imageFromMap.Save(localdata + "\\printTemp.tif", false, ImageType.TIFF_FILE); XImage image = XImage.FromFile(localdata + "\\printTemp.tif"); // Left position in point double x = (dx - image.PixelWidth * 72 / image.HorizontalResolution) / 2; gfx.DrawImage(image, 0, 0, dx, dy); /* * XImage mapLayout = XImage.FromFile(localdata + "\\PrintTemplates\\A4_quer.png"); * * * double width = mapLayout.PixelWidth * 72 / mapLayout.HorizontalResolution; * double height = mapLayout.PixelHeight * 72 / mapLayout.HorizontalResolution; * * gfx.DrawImage(mapLayout, (dx - width) / 2, (dy - height) / 2, width, height); */ //outputDocument.AddPage(mapTemplateFilledOut.Pages[0]); XPdfForm form = XPdfForm.FromFile(localdata + "\\printtemp.pdf"); gfx.DrawImage(form, 0, 0); outputDocument.Save(filename); image.Dispose(); Process.Start(filename); }
/// <summary> /// Append PDF and bitmap image to result PDF file. /// </summary> public void AppendToResultPdf() { string resultFileName = Path.Combine(OutputDirectory, "~TestResult.pdf"); PdfDocument pdfResultDocument = null; if (File.Exists(resultFileName)) { pdfResultDocument = PdfReader.Open(resultFileName, PdfDocumentOpenMode.Modify); } else { pdfResultDocument = new PdfDocument(); pdfResultDocument.PageLayout = PdfPageLayout.SinglePage; #if GDI pdfResultDocument.Info.Title = "PDFsharp Unit Tests based on GDI+"; #endif #if WPF pdfResultDocument.Info.Title = "PDFsharp Unit Tests based on WPF"; #endif pdfResultDocument.Info.Author = "Stefan Lange"; } PdfPage page = pdfResultDocument.AddPage(); page.Orientation = PageOrientation.Landscape; XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawRectangle(XBrushes.GhostWhite, new XRect(0, 0, 1000, 1000)); double x1 = XUnit.FromMillimeter((297 - 2 * WidthInMillimeter) / 3); double x2 = XUnit.FromMillimeter((297 - 2 * WidthInMillimeter) / 3 * 2 + WidthInMillimeter); double y = XUnit.FromMillimeter((210 - HeightInMillimeter) / 2); double yt = XUnit.FromMillimeter(HeightInMillimeter) + y + 20; gfx.DrawString(String.Format("PDFsharp Unit Test '{0}'", this.Name), new XFont("Arial", 9, XFontStyle.Bold), XBrushes.DarkRed, new XPoint(x1, 30)); // Draw the PDF result #if GDI //gfx.DrawString("What you see: A PDF form created with PDFsharp based on GDI+", new XFont("Verdana", 9), XBrushes.DarkBlue, new XPoint(x1, yt)); string subtitle = "This is a PDF form created with PDFsharp based on GDI+"; #endif #if WPF //gfx.DrawString("What you see: A PDF form created with PDFsharp based on WPF", new XFont("Verdana", 9), XBrushes.DarkBlue, new XPoint(x1, yt)); string subtitle = "This is a PDF form created with PDFsharp based on WPF"; #endif gfx.DrawString(subtitle, new XFont("Arial", 8), XBrushes.DarkBlue, new XRect(x1, yt, WidthInPoint, 0), XStringFormats.Default); XPdfForm form = XPdfForm.FromFile(Path.Combine(OutputDirectory, Name + ".pdf")); gfx.DrawImage(form, new XPoint(x1, y)); // Draw the result bitmap #if GDI //gfx.DrawString("What you see: A bitmap image created with PDFsharp based on GDI+", new XFont("Verdana", 9), XBrushes.DarkBlue, new XPoint(x2, yt)); subtitle = "As a reference, this is a bitmap image created with PDFsharp based on GDI+"; #endif #if WPF //gfx.DrawString("What you see: A bitmap image created with PDFsharp based on WPF", new XFont("Verdana", 9), XBrushes.DarkBlue, new XPoint(x2, yt)); subtitle = "As a reference, this is a bitmap image created with PDFsharp based on WPF"; #endif gfx.DrawString(subtitle, new XFont("Arial", 8), XBrushes.DarkBlue, new XRect(x2, yt, WidthInPoint, 0), XStringFormats.Default); XImage image = XImage.FromFile(Path.Combine(OutputDirectory, Name + ".png")); image.Interpolate = false; gfx.DrawImage(image, new XPoint(x2, y)); pdfResultDocument.Save(resultFileName); }
/// <summary> /// It shows that add external pages with two pages. /// </summary> public void Concatenate3(string checkDir) { if (!Directory.Exists(checkDir)) { return; } string outputDir = Path.Combine(checkDir, "result"); if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } string[] files = Directory.GetFiles(checkDir, "*.pdf", SearchOption.TopDirectoryOnly); if (files.Length == 0) { Console.WriteLine("no pdf files."); return; } Stopwatch sw = new Stopwatch(); sw.Start(); //get total pages int totalNoPages = 0; foreach (string file in files) { using (PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.ReadOnly)) { totalNoPages += inputDocument.PageCount; } } sw.Stop(); Console.WriteLine(string.Format("RunTime of get total no pages : {0}s", sw.ElapsedMilliseconds / 1000.0)); //Two Pages on One int newTotalNoPages = totalNoPages / 2 + (totalNoPages % 2 == 0 ? 0 : 1); int pageIdx = 0; // Open the output document using (PdfDocument outputDocument = new PdfDocument()) { outputDocument.PageLayout = PdfPageLayout.SinglePage; // For checking the file size uncomment next line. outputDocument.Options.CompressContentStreams = true; XRect box; XGraphics gfx; bool nextFile = false; for (int fileIdx = 0; fileIdx < files.Length; fileIdx++) { sw.Start(); string file = files[fileIdx]; string fileName = Path.GetFileNameWithoutExtension(file); // Open the external document as XPdfForm object using (XPdfForm form = XPdfForm.FromFile(file)) { int startIdx = nextFile ? 1 : 0; nextFile = false; int pgCount = form.PageCount; for (int idx = startIdx; idx < form.PageCount; idx += 2) { // Add a new page to the output document PdfPage page = outputDocument.AddPage(); page.Orientation = PageOrientation.Landscape; double width = page.Width; double height = page.Height; gfx = XGraphics.FromPdfPage(page); // Set page number (which is one-based) form.PageNumber = idx + 1; box = new XRect(0, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Write document file name and page number on each page DrawPageIndexBottomCenter(gfx, box, string.Format("Pg.{1}/{2} of {0}", fileName, idx + 1, pgCount)); if (idx + 1 < form.PageCount) { // Set page number (which is one-based) form.PageNumber = idx + 2; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Write document file name and page number on each page DrawPageIndexBottomCenter(gfx, box, string.Format("Pg.{1}/{2} of {0}", fileName, idx + 2, pgCount)); } else { //last page. nextFile = true; if (fileIdx + 1 < files.Length) { string nextFileName = Path.GetFileNameWithoutExtension(files[fileIdx + 1]); using (XPdfForm nextPdfFileForm = XPdfForm.FromFile(files[fileIdx + 1])) { nextPdfFileForm.PageNumber = 1; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(nextPdfFileForm, box); // Write document file name and page number on each page DrawPageIndexBottomCenter(gfx, box, string.Format("Pg.{1}/{2} of {0}", nextFileName, 1, nextPdfFileForm.PageCount)); } } } string pageInfo = string.Format("Pg.{0}/{1}", ++pageIdx, newTotalNoPages); DrawPageIndex(gfx, pageInfo); } sw.Stop(); Console.WriteLine(string.Format("RunTime of file name : {0} - {1}s", fileName, sw.ElapsedMilliseconds / 1000.0)); } } // Save the document... string filename = Path.Combine(outputDir, "ConcatenatedDocument3.pdf"); outputDocument.Save(filename); } }
/// <summary> /// Imports the pages as form X objects. /// Note that this technique copies only the visual content and the hyperlinks do not work. /// </summary> public void Combine1(string checkDir) { if (!Directory.Exists(checkDir)) { return; } string outputDir = Path.Combine(checkDir, "result"); if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } string[] files = Directory.GetFiles(checkDir, "*.pdf", SearchOption.TopDirectoryOnly); if (files.Length < 2) { Console.WriteLine("at least two pdf file in the folder."); return; } // Create the output document // Create the output document using (PdfDocument outputDocument = new PdfDocument()) { using (PdfDocument inputDocument1 = PdfReader.Open(files[0], PdfDocumentOpenMode.Import)) { using (PdfDocument inputDocument2 = PdfReader.Open(files[1], PdfDocumentOpenMode.Import)) { string filename1 = Path.GetFileNameWithoutExtension(files[0]); string filename2 = Path.GetFileNameWithoutExtension(files[1]); // Show consecutive pages facing outputDocument.PageLayout = PdfPageLayout.TwoPageLeft; XFont font = new XFont("Verdana", 10, XFontStyle.Bold); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; XGraphics gfx; XRect box; // Open the external documents as XPdfForm objects. Such objects are // treated like images. By default the first page of the document is // referenced by a new XPdfForm. XPdfForm form1 = XPdfForm.FromFile(files[0]); XPdfForm form2 = XPdfForm.FromFile(files[1]); int count = Math.Max(form1.PageCount, form2.PageCount); for (int idx = 0; idx < count; idx++) { // Add two new pages to the output document PdfPage page1 = outputDocument.AddPage(); PdfPage page2 = outputDocument.AddPage(); if (form1.PageCount > idx) { // Get a graphics object for page1 gfx = XGraphics.FromPdfPage(page1); // Set page number (which is one-based) form1.PageNumber = idx + 1; // Draw the page identified by the page number like an image gfx.DrawImage(form1, new XRect(0, 0, form1.PointWidth, form1.PointHeight)); // Write document file name and page number on each page box = page1.MediaBox.ToXRect(); box.Inflate(0, -10); gfx.DrawString(String.Format("{0} • {1}", filename1, idx + 1), font, XBrushes.Red, box, format); } // Same as above for second page if (form2.PageCount > idx) { gfx = XGraphics.FromPdfPage(page2); form2.PageNumber = idx + 1; gfx.DrawImage(form2, new XRect(0, 0, form2.PointWidth, form2.PointHeight)); box = page2.MediaBox.ToXRect(); box.Inflate(0, -10); gfx.DrawString(String.Format("{0} • {1}", filename2, idx + 1), font, XBrushes.Red, box, format); } } // Save the document... string filename = Path.Combine(outputDir, "CompareDocument2.pdf"); outputDocument.Save(filename); } } } }
public static bool AddWatermarkOnFrontAndDwgOnBackOfPartDwg(string fileName) { try { // Create the output document PdfDocument outputDocument = new PdfDocument(); outputDocument.PageLayout = PdfPageLayout.SinglePage; XFont font = new XFont("Verdana", 8, XFontStyle.Bold); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; XGraphics gfx; XRect box; // Open the external document as XPdfForm object XPdfForm form = XPdfForm.FromFile(fileName); PdfPage fullsizePage = form.Page; for (int idx = 0; idx < form.PageCount; idx += 2) { // Add a new page to the output document PdfPage page = outputDocument.AddPage(); page.Orientation = PageOrientation.Portrait; double width = page.Width; double height = page.Height; gfx = XGraphics.FromPdfPage(page); // Set page number (which is one-based) form.PageNumber = idx + 1; double originalWidth = form.PixelWidth; double originalHeight = form.PixelHeight; double ratio = form.PixelWidth / form.PixelHeight; double newWidth, newHeight = 0; double startX, startY = 0; if (fullsizePage.Orientation == PageOrientation.Portrait && fullsizePage.Rotate == 90) { newWidth = 435; //306 newHeight = 500; startX = 25; //100 startY = -100; } else { newWidth = 300; newHeight = 400; startX = 150; startY = 0; } //if (originalWidth == 612) //{ // newWidth = 306; // startX = 153; //} //else //{ // newWidth = 500; // startX = 56; //} box = new XRect(startX, startY, newWidth, newHeight); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); if (idx + 1 < form.PageCount) { // Set page number (which is one-based) form.PageNumber = idx + 2; box = new XRect(startX, height / 2, newWidth, height / 2); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); } // add a full size dwg on the back the page outputDocument.AddPage(fullsizePage); } // Save output document outputDocument.Save(fileName); return(true); } catch (Exception ex) { return(false); } }
public static bool AddWatermarkOnFrontAndDwgOnBackOfAssyDwg(string fileName, string watermark) { try { string filename = fileName; // Create the output document PdfDocument outputDocument = new PdfDocument(); PdfDocument tempDocument = new PdfDocument(); outputDocument.PageLayout = PdfPageLayout.SinglePage; tempDocument.PageLayout = PdfPageLayout.SinglePage; XFont font = new XFont("Verdana", 8, XFontStyle.Bold); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; XGraphics gfx; XRect box; // Open the external document as XPdfForm object XPdfForm form = XPdfForm.FromFile(filename); for (int idx = 0; idx < form.PageCount; idx++) { form.PageNumber = idx + 1; PdfPage fullsizePage = form.Page; // Add a new page to the output document PdfPage page = outputDocument.AddPage(); page.Orientation = PageOrientation.Portrait; double width = page.Width; double height = page.Height; gfx = XGraphics.FromPdfPage(page); // Set page number (which is one-based) form.PageNumber = idx + 1; double originalWidth = form.PixelWidth; double originalHeight = form.PixelHeight; double ratio = form.PixelWidth / form.PixelHeight; double newWidth, newHeight = 0; double startX, startY = 0; if (fullsizePage.Orientation == PageOrientation.Portrait && fullsizePage.Rotate == 90) { newWidth = 435; //306 newHeight = 500; startX = 25; //100 startY = -100; } else { newWidth = 300; newHeight = 400; startX = 150; startY = 0; } box = new XRect(startX, startY, newWidth, newHeight); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // create a temporary watermark page PdfPage watermarkPage = new PdfPage(tempDocument); watermarkPage.Height = page.Height; watermarkPage.Width = page.Width; if (page.Rotate == 90 && page.Orientation == PdfSharp.PageOrientation.Portrait) { watermarkPage.Orientation = PdfSharp.PageOrientation.Landscape; watermarkPage.Rotate = 0; } font = new XFont("Times New Roman", 15, XFontStyle.Bold); XTextFormatter tf = new XTextFormatter(gfx); XRect rect = new XRect(40, height / 2, width - 40, height - 75); XBrush brush = new XSolidBrush(XColor.FromArgb(255, 0, 0, 0)); tf.DrawString(watermark, font, brush, rect, XStringFormats.TopLeft); gfx = XGraphics.FromPdfPage(watermarkPage); box = new XRect(startX, height / 2, newWidth, height / 2); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // add a full size dwg on the back of every page outputDocument.AddPage(fullsizePage); } // Save output document outputDocument.Save(fileName); return(true); } catch (Exception ex) { return(false); } }
static void Main() { // Create a new PDF document PdfDocument document = new PdfDocument(); // Create a font XFont font = new XFont("Verdana", 16); // Create a new page PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page, XPageDirection.Downwards); gfx.DrawString("XPdfForm Sample", font, XBrushes.DarkGray, 15, 25, XStringFormats.Default); // Step 1: Create an XForm and draw some graphics on it // Create an empty XForm object with the specified width and height // A form is bound to its target document when it is created. The reason is that the form can // share fonts and other objects with its target document. XForm form = new XForm(document, XUnit.FromMillimeter(70), XUnit.FromMillimeter(55)); // Create an XGraphics object for drawing the contents of the form. XGraphics formGfx = XGraphics.FromForm(form); // Draw a large transparent rectangle to visualize the area the form occupies XColor back = XColors.Orange; back.A = 0.2; XSolidBrush brush = new XSolidBrush(back); formGfx.DrawRectangle(brush, -10000, -10000, 20000, 20000); // On a form you can draw... // ... text formGfx.DrawString("Text, Graphics, Images, and Forms", new XFont("Verdana", 10, XFontStyle.Regular), XBrushes.Navy, 3, 0, XStringFormats.TopLeft); XPen pen = XPens.LightBlue.Clone(); pen.Width = 2.5; // ... graphics like Bézier curves formGfx.DrawBeziers(pen, XPoint.ParsePoints("30,120 80,20 100,140 175,33.3")); // ... raster images like GIF files XGraphicsState state = formGfx.Save(); formGfx.RotateAtTransform(17, new XPoint(30, 30)); formGfx.DrawImage(XImage.FromFile("../../../../../../dev/XGraphicsLab/images/Test.gif"), 20, 20); formGfx.Restore(state); // ... and forms like XPdfForm objects state = formGfx.Save(); formGfx.RotateAtTransform(-8, new XPoint(165, 115)); formGfx.DrawImage(XPdfForm.FromFile("../../../../../PDFs/SomeLayout.pdf"), new XRect(140, 80, 50, 50 * Math.Sqrt(2))); formGfx.Restore(state); // When you finished drawing on the form, dispose the XGraphic object. formGfx.Dispose(); // Step 2: Draw the XPdfForm on your PDF page like an image // Draw the form on the page of the document in its original size gfx.DrawImage(form, 20, 50); #if true // Draw it stretched gfx.DrawImage(form, 300, 100, 250, 40); // Draw and rotate it const int d = 25; for (int idx = 0; idx < 360; idx += d) { gfx.DrawImage(form, 300, 480, 200, 200); gfx.RotateAtTransform(d, new XPoint(300, 480)); } #endif // Save the document... const string filename = "XForms_tempfile.pdf"; document.Save(filename); // ...and start a viewer. Process.Start(filename); }
/// <summary> /// It shows that add external pages with two pages. /// File by file, if page number is odd, with blank page. /// </summary> public void Concatenate1(string checkDir) { if (!Directory.Exists(checkDir)) { return; } string outputDir = Path.Combine(checkDir, "result"); if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } string[] files = Directory.GetFiles(checkDir, "*.pdf", SearchOption.TopDirectoryOnly); Stopwatch sw = new Stopwatch(); sw.Start(); //get total pages int totalNoPages = 0; foreach (string file in files) { using (PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.ReadOnly)) { totalNoPages += inputDocument.PageCount; } } sw.Stop(); Console.WriteLine(string.Format("RunTime of get total no pages : {0}s", sw.ElapsedMilliseconds / 1000.0)); // Open the output document using (PdfDocument outputDocument = new PdfDocument()) { outputDocument.PageLayout = PdfPageLayout.SinglePage; // For checking the file size uncomment next line. outputDocument.Options.CompressContentStreams = true; XRect box; XGraphics gfx; int number = 0; // Iterate files foreach (string file in files) { sw.Start(); string fileName = Path.GetFileNameWithoutExtension(file); // Open the external document as XPdfForm object using (XPdfForm form = XPdfForm.FromFile(file)) { for (int idx = 0; idx < form.PageCount; idx += 2) { // Add a new page to the output document PdfPage page = outputDocument.AddPage(); page.Orientation = PageOrientation.Landscape; double width = page.Width; double height = page.Height; //int rotate = page.Elements.GetInteger("/Rotate"); gfx = XGraphics.FromPdfPage(page); // Set page number (which is one-based) form.PageNumber = idx + 1; box = new XRect(0, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Write document file name and page number on each page DrawPageIndexBottomCenter(gfx, box, string.Format("- {0} - {1} -", fileName, idx + 1)); if (idx + 1 < form.PageCount) { // Set page number (which is one-based) form.PageNumber = idx + 2; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Write document file name and page number on each page DrawPageIndexBottomCenter(gfx, box, string.Format("- {0} - {1} -", fileName, idx + 2)); } string pageInfo = string.Format("Pg.{1}/{2} of {0} • Pg.{3}/{4}", fileName, idx + 1, form.PageCount, ++number, totalNoPages); DrawPageIndex(gfx, pageInfo); } sw.Stop(); Console.WriteLine(string.Format("RunTime of file name : {0} - {1}s", fileName, sw.ElapsedMilliseconds / 1000.0)); } } // Save the document... string filename = Path.Combine(outputDir, "ConcatenatedDocument1.pdf"); outputDocument.Save(filename); } }
/// <summary> /// Implements the PDF file to XPS file conversion. /// </summary> public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument) { if (String.IsNullOrEmpty(xpsFilename)) { throw new ArgumentNullException("xpsFilename"); } if (String.IsNullOrEmpty(pdfFilename)) { pdfFilename = xpsFilename; if (IOPath.HasExtension(pdfFilename)) { pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.')); } pdfFilename += ".pdf"; } XpsDocument xpsDocument = null; try { xpsDocument = XpsDocument.Open(xpsFilename); FixedDocument fixedDocument = xpsDocument.GetDocument(); PdfDocument pdfDocument = new PdfDocument(); PdfRenderer renderer = new PdfRenderer(); int pageIndex = 0; foreach (FixedPage page in fixedDocument.Pages) { if (page == null) { continue; } Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = renderer.CreatePage(pdfDocument, page); renderer.RenderPage(pdfPage, page); pageIndex++; #if DEBUG // stop at page... if (pageIndex == 50) { break; } #endif } pdfDocument.Save(pdfFilename); xpsDocument.Close(); xpsDocument = null; if (createComparisonDocument) { System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, FileAccess.Read); System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence(); if (docSeq == null) { throw new InvalidOperationException("docSeq"); } XPdfForm form = XPdfForm.FromFile(pdfFilename); PdfDocument pdfComparisonDocument = new PdfDocument(); pageIndex = 0; foreach (PdfPage page in pdfDocument.Pages) { if (page == null) { continue; } Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = /*renderer.CreatePage(pdfComparisonDocument, page);*/ pdfComparisonDocument.AddPage(); double width = page.Width; double height = page.Height; pdfPage.Width = page.Width * 2; pdfPage.Height = page.Height; DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex); //byte[] png = PngFromPage(docPage, 96); BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2); XImage image = XImage.FromBitmapSource(bmsource); XGraphics gfx = XGraphics.FromPdfPage(pdfPage); form.PageIndex = pageIndex; gfx.DrawImage(form, 0, 0, width, height); gfx.DrawImage(image, width, 0, width, height); //renderer.RenderPage(pdfPage, page); pageIndex++; #if DEBUG // stop at page... if (pageIndex == 50) { break; } #endif } string pdfComparisonFilename = pdfFilename; if (IOPath.HasExtension(pdfComparisonFilename)) { pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.')); } pdfComparisonFilename += "-comparison.pdf"; pdfComparisonDocument.ViewerPreferences.FitWindow = true; //pdfComparisonDocument.PageMode = PdfPageMode. pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage; pdfComparisonDocument.Save(pdfComparisonFilename); } } catch (Exception ex) { Debug.WriteLine(ex.Message); if (xpsDocument != null) { xpsDocument.Close(); } throw; } finally { if (xpsDocument != null) { xpsDocument.Close(); } } }
/// <summary> /// Renders the content of the page. /// </summary> public void Render(XGraphics gfx) { XRect rect; XPen pen; double x = 50, y = 100; XFont fontH1 = new XFont("Times", 18, XFontStyle.Bold); XFont font = new XFont("Times", 12); XFont fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic); double ls = font.GetHeight(gfx); // Draw some text gfx.DrawString("Create PDF on the fly with PDFsharp", fontH1, XBrushes.Black, x, x); gfx.DrawString("With PDFsharp you can use the same code to draw graphic, " + "text and images on different targets.", font, XBrushes.Black, x, y); y += ls; gfx.DrawString("The object used for drawing is the XGraphics object.", font, XBrushes.Black, x, y); y += 2 * ls; // Draw an arc pen = new XPen(XColors.Red, 4); pen.DashStyle = XDashStyle.Dash; gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120); // Draw a star XGraphicsState gs = gfx.Save(); gfx.TranslateTransform(x + 140, y + 30); for (int idx = 0; idx < 360; idx += 10) { gfx.RotateTransform(10); gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0); } gfx.Restore(gs); // Draw a rounded rectangle rect = new XRect(x + 230, y, 100, 60); pen = new XPen(XColors.DarkBlue, 2.5); XColor color1 = XColor.FromKnownColor(KnownColor.DarkBlue); XColor color2 = XColors.Red; XLinearGradientBrush lbrush = new XLinearGradientBrush(rect, color1, color2, XLinearGradientMode.Vertical); gfx.DrawRoundedRectangle(pen, lbrush, rect, new XSize(10, 10)); // Draw a pie pen = new XPen(XColors.DarkOrange, 1.5); pen.DashStyle = XDashStyle.Dot; gfx.DrawPie(pen, XBrushes.Blue, x + 360, y, 100, 60, -130, 135); // Draw some more text y += 60 + 2 * ls; gfx.DrawString("With XGraphics you can draw on a PDF page as well as " + "on any System.Drawing.Graphics object.", font, XBrushes.Black, x, y); y += ls * 1.1; gfx.DrawString("Use the same code to", font, XBrushes.Black, x, y); x += 10; y += ls * 1.1; gfx.DrawString("• draw on a newly created PDF page", font, XBrushes.Black, x, y); y += ls; gfx.DrawString("• draw above or beneath of the content of an existing PDF page", font, XBrushes.Black, x, y); y += ls; gfx.DrawString("• draw in a window", font, XBrushes.Black, x, y); y += ls; gfx.DrawString("• draw on a printer", font, XBrushes.Black, x, y); y += ls; gfx.DrawString("• draw in a bitmap image", font, XBrushes.Black, x, y); x -= 10; y += ls * 1.1; gfx.DrawString("You can also import an existing PDF page and use it like " + "an image, e.g. draw it on another PDF page.", font, XBrushes.Black, x, y); y += ls * 1.1 * 2; gfx.DrawString("Imported PDF pages are neither drawn nor printed; create a " + "PDF file to see or print them!", fontItalic, XBrushes.Firebrick, x, y); y += ls * 1.1; gfx.DrawString("Below this text is a PDF form that will be visible when " + "viewed or printed with a PDF viewer.", fontItalic, XBrushes.Firebrick, x, y); y += ls * 1.1; XGraphicsState state = gfx.Save(); XRect rcImage = new XRect(100, y, 100, 100 * Math.Sqrt(2)); gfx.DrawRectangle(XBrushes.Snow, rcImage); gfx.DrawImage(XPdfForm.FromFile("../../../../../PDFs/SomeLayout.pdf"), rcImage); gfx.Restore(state); }
// This sample shows how to place two pages of an existing document on // one landscape orientated page of a new document. protected override void DoWork() { // Get a fresh copy of the sample PDF file string filename = "Portable Document Format.pdf"; File_Copy(Path.Combine("AltData/PDFsharp/PDFs/", filename), Path.Combine(Directory.GetCurrentDirectory(), filename), true); // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show single pages // (Note: one page contains two pages from the source document) outputDocument.PageLayout = PdfPageLayout.SinglePage; XFont font = new XFont("Verdana", 8, XFontStyle.Bold); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; XGraphics gfx; XRect box; // Open the external document as XPdfForm object XPdfForm form = XPdfForm.FromFile(filename); for (int idx = 0; idx < form.PageCount; idx += 2) { // Add a new page to the output document PdfPage page = outputDocument.AddPage(); page.Orientation = PageOrientation.Landscape; double width = page.Width; double height = page.Height; //NotUsed int rotate = page.Elements.GetInteger("/Rotate"); gfx = XGraphics.FromPdfPage(page); // Set page number (which is one-based) form.PageNumber = idx + 1; box = new XRect(0, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Write document file name and page number on each page box.Inflate(0, -10); gfx.DrawString(String.Format("- {1} -", filename, idx + 1), font, XBrushes.Red, box, format); if (idx + 1 < form.PageCount) { // Set page number (which is one-based) form.PageNumber = idx + 2; box = new XRect(width / 2, 0, width / 2, height); // Draw the page identified by the page number like an image gfx.DrawImage(form, box); // Write document file name and page number on each page box.Inflate(0, -10); gfx.DrawString(String.Format("- {1} -", filename, idx + 2), font, XBrushes.Red, box, format); } } // Save the document... filename = "TwoPagesOnOne_tempfile.pdf"; outputDocument.Save(filename); // ...and start a viewer. Diagnostics.ProcessHelper.Start(filename); }