private static void EscreverVerso(PdfDocument outputDocument, XPdfForm form, UsuarioCertificadoCertame certificadoUsuario, XFont font, XStringFormat format) { if (form.PageCount > 1) { var paginaVerso = outputDocument.AddPage(); paginaVerso.Orientation = PageOrientation.Landscape; paginaVerso.Size = PageSize.A4; form.PageNumber = 2; var posicaoId = new BMPosicaoDadoCertificadoCertame().ObterPorDadoAno("id", certificadoUsuario.CertificadoCertame.Ano); if (posicaoId == null) { throw new Exception("Posição de dado obrigatório não informada no verso"); } var gfx = XGraphics.FromPdfPage(paginaVerso); gfx.DrawImage(form, new XRect(0, 0, form.PointWidth, form.PointHeight)); EscreverDado(paginaVerso, posicaoId, gfx, font, format, certificadoUsuario.Chave); } }
public override void Layout(XPdfForm inputPdf, string inputPath, string outputPath, PaperTarget paperTarget, bool rightToLeft, bool showCropMarks) { if (!showCropMarks) { File.Copy(inputPath, outputPath, true); // we don't have any value to add, so just deliver a copy of the original } else { //_rightToLeft = rightToLeft; _inputPdf = inputPdf; _showCropMarks = showCropMarks; PdfDocument outputDocument = new PdfDocument(); outputDocument.PageLayout = PdfPageLayout.SinglePage; _paperWidth = _inputPdf.PixelWidth; _paperHeight = _inputPdf.PixelHeight; // if (showCropMarks) // { // _paperWidth.Millimeter += (2.0 * LayoutMethod.kMillimetersBetweenTrimAndMediaBox); // _paperHeight.Millimeter += (2.0 * LayoutMethod.kMillimetersBetweenTrimAndMediaBox); // } for (int idx = 1; idx <= _inputPdf.PageCount; idx++) { using (XGraphics gfx = GetGraphicsForNewPage(outputDocument)) { DrawPage(gfx, idx); } } outputDocument.Save(outputPath); } }
private static void EscreverFrente(PdfDocument outputDocument, XPdfForm form, UsuarioCertificadoCertame certificadoUsuario, XFont font, XStringFormat format) { var paginaFrente = outputDocument.AddPage(); paginaFrente.Orientation = PageOrientation.Landscape; paginaFrente.Size = PageSize.A4; form.PageNumber = 1; var manterPosicaoDado = new BMPosicaoDadoCertificadoCertame(); var posicaoNome = manterPosicaoDado.ObterPorDadoAno("nome", certificadoUsuario.CertificadoCertame.Ano); var posicaoCpf1 = manterPosicaoDado.ObterPorDadoAno("cpf1", certificadoUsuario.CertificadoCertame.Ano); var posicaoCpf2 = manterPosicaoDado.ObterPorDadoAno("cpf2", certificadoUsuario.CertificadoCertame.Ano); if (posicaoNome == null || posicaoCpf1 == null || posicaoCpf2 == null) { throw new Exception("Posição de dado obrigatório não informada na frente"); } var gfx = XGraphics.FromPdfPage(paginaFrente); gfx.DrawImage(form, new XRect(0, 0, form.PointWidth, form.PointHeight)); EscreverDado(paginaFrente, posicaoNome, gfx, font, format, certificadoUsuario.Usuario.Nome); EscreverDado(paginaFrente, posicaoCpf1, gfx, font, format, certificadoUsuario.Usuario.CPF.Substring(0, 9).Insert(3, ".").Insert(7, ".")); EscreverDado(paginaFrente, posicaoCpf2, gfx, font, format, certificadoUsuario.Usuario.CPF.Substring(9, 2)); if (certificadoUsuario.CertificadoCertame.Data.HasValue) { var data = certificadoUsuario.CertificadoCertame.Data.Value; var dataFormatada = string.Format("{0} de {1} de {2}", data.Day.ToString().PadLeft(2, '0'), data.ObterNomeMes(), data.Year); var posicaoData = manterPosicaoDado.ObterPorDadoAno("data", certificadoUsuario.CertificadoCertame.Ano); EscreverDado(paginaFrente, posicaoData, gfx, font, format, dataFormatada); } if (!string.IsNullOrWhiteSpace(certificadoUsuario.CertificadoCertame.NomeCertificado)) { var posicaoNomeCertificado = manterPosicaoDado.ObterPorDadoAno("nomecertificado", certificadoUsuario.CertificadoCertame.Ano); // Somente nesse caso, só insere o nome no PDF caso tenha o dado, pois alguns PDFs possuem o // nome neles, mas o campo "Nome" é obrigatório em todos os certificados. if (posicaoNomeCertificado != null) { var fontNomeCertificado = new XFont("Verdana", 13, XFontStyle.Bold); EscreverDado(paginaFrente, posicaoNomeCertificado, gfx, fontNomeCertificado, format, certificadoUsuario.CertificadoCertame.NomeCertificado.ToUpper()); } } }
internal override void Render() { RenderFilling(); HtmlFormFormatInfo formatInfo = (HtmlFormFormatInfo)_renderInfo.FormatInfo; Area contentArea = _renderInfo.LayoutInfo.ContentArea; XRect destRect = new XRect(contentArea.X, contentArea.Y, formatInfo.Width, formatInfo.Height); if (formatInfo.Failure == HtmlFormFailure.None) { XImage xImage = null; try { // TODO: Falhar com _form.Content vazio // TODO: Add CropX, CropY, etc... XRect srcRect = new XRect(0, 0, formatInfo.Width, formatInfo.Height); var config = new PdfGenerateConfig { ManualPageSize = new XSize(formatInfo.Width, formatInfo.Height), MarginBottom = 0, MarginTop = 0, MarginLeft = 0, MarginRight = 0 }; using (var htmlPdfDoc = PdfGenerator.GeneratePdf(_form.Content, config)) { using (var pdfStream = new MemoryStream()) { htmlPdfDoc.Save(pdfStream); xImage = XPdfForm.FromStream(pdfStream); _gfx.DrawImage(xImage, destRect, srcRect, XGraphicsUnit.Point); } } } catch (Exception) { RenderFailureImage(destRect); } finally { if (xImage != null) { xImage.Dispose(); } } } else { RenderFailureImage(destRect); } RenderLine(); }
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); }
public MemoryStream Message2Pdf(MimeMessage message) { MemoryStream msMail = new MemoryStream(); string html = message.GetTextBody(MimeKit.Text.TextFormat.Html); string txt = message.GetTextBody(MimeKit.Text.TextFormat.Text); HtmlToPdf converter = new HtmlToPdf(); SelectPdf.PdfDocument pdfdok = null; if (html != null) { pdfdok = converter.ConvertHtmlString(html); } else { if (string.IsNullOrEmpty(txt)) { txt = "Tom email"; } pdfdok = converter.ConvertHtmlString(txt); } pdfdok.Save(msMail); msMail.Position = 0; XPdfForm form = XPdfForm.FromStream(msMail); PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument(); XGraphics gfx; int count = form.PageCount; for (int idx = 0; idx < count; idx++) { PdfSharp.Pdf.PdfPage page = outputDocument.AddPage(); if (form.PageCount > idx) { // Get a graphics object for page gfx = XGraphics.FromPdfPage(page); if (idx == 0) { DrawPageHeading(page, gfx, message); // Draw the page like an image gfx.DrawImage(form, new XRect(form.PointWidth * 0.02, form.PointHeight * 0.10, form.PointWidth * 0.90, form.PointHeight * 0.90)); } else { gfx.DrawImage(form, new XRect(form.PointWidth, form.PointHeight, form.PointWidth, form.PointHeight)); } } } msMail = new MemoryStream(); outputDocument.Save(msMail, false); return(msMail); }
/// <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> /// Create the plot, and convert it to an XImage. Remember to dispose of the returned object, and that this MUST be run with threading ApartmentState.STA /// </summary> /// <param name="results"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="resolution"></param> /// <returns></returns> private XImage CreatePlot(List <CompoundData> results, int width, int height, int resolution = 96) { var plot = Plotting.CreatePlot(results, DatasetName, Plotting.ExportFormat.PDF); using (var memStream = new MisbehavingMemoryStream()) { memStream.PreventDispose = true; Plotting.SavePlotToPdf(memStream, plot, width, height); memStream.Seek(0, SeekOrigin.Begin); var pdfForm = XPdfForm.FromStream(memStream); memStream.PreventDispose = false; return(pdfForm); } }
/// <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 }
/// <summary> /// Gets a PdfFormXObject from an XPdfForm. Because the returned objects must be unique, always /// a new instance of PdfFormXObject is created if none exists for the specified form. /// </summary> public PdfFormXObject GetForm(XForm form) { // If the form already has a PdfFormXObject, return it. if (form._pdfForm != null) { Debug.Assert(form.IsTemplate, "An XPdfForm must not have a PdfFormXObject."); if (ReferenceEquals(form._pdfForm.Owner, Owner)) { return(form._pdfForm); } //throw new InvalidOperationException("Because of a current limitation of PDFsharp an XPdfForm object can be used only within one single PdfDocument."); // Dispose PdfFromXObject when document has changed form._pdfForm = null; } XPdfForm pdfForm = form as XPdfForm; if (pdfForm != null) { // Is the external PDF file from which is imported already known for the current document? Selector selector = new Selector(form); PdfImportedObjectTable importedObjectTable; if (!_forms.TryGetValue(selector, out importedObjectTable)) { // No: Get the external document from the form and create ImportedObjectTable. PdfDocument doc = pdfForm.ExternalDocument; importedObjectTable = new PdfImportedObjectTable(Owner, doc); _forms[selector] = importedObjectTable; } PdfFormXObject xObject = importedObjectTable.GetXObject(pdfForm.PageNumber); if (xObject == null) { xObject = new PdfFormXObject(Owner, importedObjectTable, pdfForm); importedObjectTable.SetXObject(pdfForm.PageNumber, xObject); } return(xObject); } Debug.Assert(form.GetType() == typeof(XForm)); form._pdfForm = new PdfFormXObject(Owner, form); return(form._pdfForm); }
/// <summary> /// Produce a new pdf with rearranged pages /// </summary> /// <param name="inputPdf">the source pdf</param> /// <param name="inputPath">the path to the source pdf (used by null layouter)</param> /// <param name="outputPath"></param> /// <param name="paperTarget">The size of the pages of the output pdf</param> /// <param name="rightToLeft">Is this a right-to-left language? Might be better-named "backToFront"</param> /// <param name="showCropMarks">For commercial printing, make a Trimbox, BleedBox, and crop marks</param> public virtual void Layout(XPdfForm inputPdf, string inputPath, string outputPath, PaperTarget paperTarget, bool rightToLeft, bool showCropMarks) { _rightToLeft = rightToLeft; _inputPdf = inputPdf; _showCropMarks = showCropMarks; 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; // Determine width and height SetPaperSize(paperTarget); int inputPages = _inputPdf.PageCount; int numberOfSheetsOfPaper = inputPages / 4; if (numberOfSheetsOfPaper * 4 < inputPages) { numberOfSheetsOfPaper += 1; } int numberOfPageSlotsAvailable = 4 * numberOfSheetsOfPaper; int vacats = numberOfPageSlotsAvailable - inputPages; LayoutInner(outputDocument, numberOfSheetsOfPaper, numberOfPageSlotsAvailable, vacats); // if(true) // foreach (PdfPage page in outputDocument.Pages) // { // // var gfx = XGraphics.FromPdfPage(page); // gfx.DrawImage(page, 0.0,0.0); // page.MediaBox = new PdfRectangle(new XPoint(m.X2, m.Y1), new XPoint(m.X1, m.Y2)); // } outputDocument.Save(outputPath); }
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; } }
public override bool GetIsEnabled(XPdfForm inputPdf) { return(IsPortrait(inputPdf)); }
/// <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); }
public static bool IsSquare(XPdfForm inputPdf) { return(inputPdf != null && inputPdf.PixelWidth == inputPdf.PixelHeight); }
internal PdfFormXObject(PdfDocument thisDocument, PdfImportedObjectTable importedObjectTable, XPdfForm form) : base(thisDocument) { Debug.Assert(ReferenceEquals(thisDocument, importedObjectTable.Owner)); Elements.SetName(Keys.Type, "/XObject"); Elements.SetName(Keys.Subtype, "/Form"); if (form.IsTemplate) { Debug.Assert(importedObjectTable == null); // TODO more initialization here??? return; } Debug.Assert(importedObjectTable != null); XPdfForm pdfForm = form; // Get import page PdfPages importPages = importedObjectTable.ExternalDocument.Pages; if (pdfForm.PageNumber < 1 || pdfForm.PageNumber > importPages.Count) { PSSR.ImportPageNumberOutOfRange(pdfForm.PageNumber, importPages.Count, form._path); } PdfPage importPage = importPages[pdfForm.PageNumber - 1]; // Import resources PdfItem res = importPage.Elements["/Resources"]; if (res != null) // unlikely but possible { #if true // Get root object PdfObject root; if (res is PdfReference) { root = ((PdfReference)res).Value; } else { root = (PdfDictionary)res; } root = ImportClosure(importedObjectTable, thisDocument, root); // If the root was a direct object, make it indirect. if (root.Reference == null) { thisDocument._irefTable.Add(root); } Debug.Assert(root.Reference != null); Elements["/Resources"] = root.Reference; #else // Get transitive closure PdfObject[] resources = importPage.Owner.Internals.GetClosure(resourcesRoot); int count = resources.Length; #if DEBUG_ for (int idx = 0; idx < count; idx++) { Debug.Assert(resources[idx].XRef != null); Debug.Assert(resources[idx].XRef.Document != null); Debug.Assert(resources[idx].Document != null); if (resources[idx].ObjectID.ObjectNumber == 12) { GetType(); } } #endif // 1st step. Already imported objects are reused and new ones are cloned. for (int idx = 0; idx < count; idx++) { PdfObject obj = resources[idx]; if (importedObjectTable.Contains(obj.ObjectID)) { // external object was already imported PdfReference iref = importedObjectTable[obj.ObjectID]; Debug.Assert(iref != null); Debug.Assert(iref.Value != null); Debug.Assert(iref.Document == Owner); // replace external object by the already clone counterpart resources[idx] = iref.Value; } else { // External object was not imported ealier and must be cloned PdfObject clone = obj.Clone(); Debug.Assert(clone.Reference == null); clone.Document = Owner; if (obj.Reference != null) { // add it to this (the importer) document Owner.irefTable.Add(clone); Debug.Assert(clone.Reference != null); // save old object identifier importedObjectTable.Add(obj.ObjectID, clone.Reference); //Debug.WriteLine("Cloned: " + obj.ObjectID.ToString()); } else { // The root object (the /Resources value) is not an indirect object Debug.Assert(idx == 0); // add it to this (the importer) document Owner.irefTable.Add(clone); Debug.Assert(clone.Reference != null); } // replace external object by its clone resources[idx] = clone; } } #if DEBUG_ for (int idx = 0; idx < count; idx++) { Debug.Assert(resources[idx].XRef != null); Debug.Assert(resources[idx].XRef.Document != null); Debug.Assert(resources[idx].Document != null); if (resources[idx].ObjectID.ObjectNumber == 12) { GetType(); } } #endif // 2nd step. Fix up indirect references that still refers to the import document. for (int idx = 0; idx < count; idx++) { PdfObject obj = resources[idx]; Debug.Assert(obj.Owner != null); FixUpObject(importedObjectTable, importedObjectTable.Owner, obj); } // Set resources key to the root of the clones Elements["/Resources"] = resources[0].Reference; #endif } // Take /Rotate into account PdfRectangle rect = importPage.Elements.GetRectangle(PdfPage.Keys.MediaBox); int rotate = importPage.Elements.GetInteger(PdfPage.Keys.Rotate); //rotate = 0; if (rotate == 0) { // Set bounding box to media box Elements["/BBox"] = rect; } else { // TODO: Have to adjust bounding box? (I think not, but I'm not sure -> wait for problem) Elements["/BBox"] = rect; // Rotate the image such that it is upright XMatrix matrix = new XMatrix(); double width = rect.Width; double height = rect.Height; matrix.RotateAtPrepend(-rotate, new XPoint(width / 2, height / 2)); if (rotate != 180) { // Translate the image such that its center lies on the center of the rotated bounding box double offset = (height - width) / 2; if (height > width) { matrix.TranslatePrepend(offset, offset); } else { matrix.TranslatePrepend(-offset, -offset); } } //string item = "[" + PdfEncoders.ToString(matrix) + "]"; //Elements[Keys.Matrix] = new PdfLiteral(item); Elements.SetMatrix(Keys.Matrix, matrix); } // Preserve filter because the content keeps unmodified PdfContent content = importPage.Contents.CreateSingleContent(); #if !DEBUG content.Compressed = true; #endif PdfItem filter = content.Elements["/Filter"]; if (filter != null) { Elements["/Filter"] = filter.Clone(); } // (no cloning needed because the bytes keep untouched) Stream = content.Stream; // new PdfStream(bytes, this); Elements.SetInteger("/Length", content.Stream.Value.Length); }
/// <summary> /// It shows that add external pages with two pages. /// First, concatenate all page into one, then plance two pages into one page. /// </summary> public void Concatenate2(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)); using (PdfDocument outputDocMid = new PdfDocument()) { foreach (string file in files) { sw.Start(); string fileName = Path.GetFileNameWithoutExtension(file); // Open the document to import pages from it. using (PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import)) { // Iterate pages int count = inputDocument.PageCount; for (int idx = 0; idx < count; idx++) { // Get the page from the external document PdfPage page = inputDocument.Pages[idx]; // and add it to the output document. // Note that the PdfPage instance returned by AddPage is a different object. page = outputDocMid.AddPage(page); // Create a graphics object for this page. To draw beneath the existing content set 'Append' to 'Prepend'. XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append); string pageInfo = string.Format("Pg.{1}/{2} of {0}", fileName, idx + 1, count); DrawPageIndexBottomCenter(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, "ConcatenatedDocument2_1.pdf"); outputDocMid.Save(filename); //Two Pages on One int newTotalNoPages = totalNoPages / 2 + (totalNoPages % 2 == 0 ? 0 : 1); using (MemoryStream stream = new MemoryStream()) { outputDocMid.Save(stream, false); using (PdfDocument mergedOutputDoc = new PdfDocument()) { mergedOutputDoc.PageLayout = PdfPageLayout.SinglePage; // For checking the file size uncomment next line. mergedOutputDoc.Options.CompressContentStreams = true; XRect box; XGraphics gfx; int number = 0; sw.Start(); using (XPdfForm form = XPdfForm.FromStream(stream)) { for (int idx = 0; idx < form.PageCount; idx += 2) { // Add a new page to the output document PdfPage page = mergedOutputDoc.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); 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); } string pageInfo = string.Format("Pg.{0}/{1}", ++number, newTotalNoPages); DrawPageIndex(gfx, pageInfo); } sw.Stop(); Console.WriteLine(string.Format("RunTime of merge : {0}s", sw.ElapsedMilliseconds / 1000.0)); } mergedOutputDoc.Save(Path.Combine(outputDir, "ConcatenatedDocument2.pdf")); } } } }
/// <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 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); }
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); }
/// <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); } }
public abstract bool GetIsEnabled(XPdfForm inputPdf);
/// <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); } }
public static bool IsLandscape(XPdfForm inputPdf) { return(inputPdf != null && inputPdf.PixelWidth > inputPdf.PixelHeight); }
/// <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); }
public static bool IsPortrait(XPdfForm inputPdf) { return(inputPdf != null && inputPdf.PixelWidth < inputPdf.PixelHeight); }