private static void SimpleText() { var document = new PdfDocument("my title..", "me.."); document.Fonts.Add(Font.Helvetica); var page = document.AddPage(); var text = page.AddText("hello world!!!", 20, Font.Helvetica, Color.DarkGreen); text.X = 10; text.Y = 700; document.Save(@"test.pdf"); Process.Start(@"test.pdf"); }
public string CreatePdf(PdfData pdfData) { if (GlobalFontSettings.FontResolver == null) { GlobalFontSettings.FontResolver = new FontResolver(_resourcesPath); } var document = new PdfDocument(); var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); AddTitleLogo(gfx, page, $"{_imagesPath}\\logo.jpg", 0, 0); AddTitleAndFooter(page, gfx, pdfData.DocumentTitle, document, pdfData); AddDescription(gfx, pdfData); AddList(gfx, pdfData); string docName = $"{_createdDocsPath}/{pdfData.DocumentName}-{DateTime.UtcNow.ToOADate()}.pdf"; document.Save(docName); return(docName); }
public byte[] GetPdfFile() { var document = new PdfDocument(); var prints = this.GetPrintImage(); foreach (var print in prints) { var page = document.AddPage(); using (var graphics = XGraphics.FromPdfPage(page)) { graphics.SmoothingMode = XSmoothingMode.HighQuality; var textFormatter = new PdfSharp.Drawing.Layout.XTextFormatter(graphics); var stream = new MemoryStream(); print.Save(stream, System.Drawing.Imaging.ImageFormat.Png); graphics.DrawImage(XImage.FromStream(stream), 0, 0, page.Width, page.Height); } } ; var pdfStream = new MemoryStream(); document.Save(pdfStream, true); return(pdfStream.ToArray()); }
public void CreateAndSavePDF() { string fileName = "SummonerProfile-" + this.name + "-" + this.id + ".pdf"; // Initialize Component PdfDocument pdf = new PdfDocument(); // Values Archive PDF pdf.Info.Title = fileName; pdf.Info.Author = this.name; pdf.Info.Subject = "resume of the player's experience " + this.name + " in the video game League of Legends."; PdfPage page = pdf.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Roboto", 14, XFontStyle.Bold); DrawPDF(pdf, page, gfx, font); // Save PDF and Show pdf.Save(fileName); Process.Start(fileName); }
public IActionResult Post(DrugSpecDTO drug) { System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); PdfDocument document = new PdfDocument(); document.Info.Title = drug.Name + " specification"; PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.Regular); gfx.DrawString(drug.Name, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height / 4), XStringFormats.Center); gfx.DrawString(drug.Description, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height / 2), XStringFormats.Center); // TODO(Jovan): Use global variable? string filename = "DrugSpecifications" + Path.DirectorySeparatorChar + drug.Name.Replace(" ", "") + ".pdf"; document.Save(filename); return(Ok()); }
private void btnbrowse_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = @"C:\"; openFileDialog1.Title = "Select PDF File"; openFileDialog1.DefaultExt = "pdf"; openFileDialog1.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { pdffile.Text = openFileDialog1.FileName.ToString(); pdf = PdfReader.Open(openFileDialog1.OpenFile(), PdfDocumentOpenMode.Import); foreach (PdfPage page in pdf.Pages) { outpdf.AddPage(page); } btnunlock.Enabled = true; } }
public void AddSpaceDoc(string path, string name, string description) { string fullname = path + @"\" + name + ".pdf"; PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont fontTitle = new XFont("Verdana", 16, XFontStyle.Bold); XFont font = new XFont("Verdana", 14, XFontStyle.Regular); // Draw the text gfx.DrawString(name, fontTitle, XBrushes.Black, new XRect(40, 20, page.Width - 40, 100), XStringFormats.Center); XRect rect = new XRect(40, 120, page.Width - 20, page.Height); XTextFormatter tf = new XTextFormatter(gfx); tf.DrawString(description, font, XBrushes.Black, rect, XStringFormats.TopLeft); document.Save(fullname); document.Dispose(); }
private void GerarPdf(string text, string filename) { // Create a new PDF document PdfDocument document = new PdfDocument(); // Create an empty page PdfPage page = document.AddPage(); // Get an XGraphics object for drawing XGraphics gfx = XGraphics.FromPdfPage(page); // Create a font XFont font = new XFont("Verdana", 20, XFontStyle.Bold); XTextFormatter tf = new XTextFormatter(gfx); // Draw the text tf.DrawString(text, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormat.TopLeft); document.Save(filename); // ...and start a viewer. Process.Start(filename); }
private void ConvertMigraDocToPdfSharp(ref PdfDocument document, Document migraDocument) { var pdfRenderer = new DocumentRenderer(migraDocument); pdfRenderer.PrepareDocument(); int pages = pdfRenderer.FormattedDocument.PageCount; var firstPage = (PdfPage)document.Pages[0].Clone(); for (int i = 1; i <= pages; ++i) { PdfPage page = i == 1 ? document.Pages[0] : document.AddPage((PdfPage)firstPage.Clone()); using (XGraphics gfx = XGraphics.FromPdfPage(page)) { // HACK² gfx.MUH = PdfFontEncoding.Unicode; // gfx.MFEH = PdfFontEmbedding.Default; pdfRenderer.RenderPage(gfx, i, PageRenderOptions.All); } } }
static PdfDocument PdfStitchDocuments(string[] pdfs) { int i = 1; int count; PdfDocument document = new PdfDocument(); PdfDocument importPdf; count = pdfs.Count(); foreach (string s in pdfs) { using (importPdf = PdfSharp.Pdf.IO.PdfReader.Open(s, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import)) { foreach (PdfPage page in importPdf.Pages) { document.AddPage(page); } Console.Write("\rStitching PDFs {0} of {1}", i++, count); } } Console.Write("\n"); return(document); }
public static void SplitPdfFile() { string filename = "testOutputMerge.pdf"; //open the file PdfDocument inputDocument = PdfReader.Open(filename, PdfDocumentOpenMode.Import); string name = Path.GetFileNameWithoutExtension(filename); for (int idx = 0; idx < inputDocument.PageCount; idx++) { // Create new document PdfDocument outputDocument = new PdfDocument(); outputDocument.Version = inputDocument.Version; outputDocument.Info.Title = String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title); outputDocument.Info.Creator = inputDocument.Info.Creator; // Add the page and save it outputDocument.AddPage(inputDocument.Pages[idx]); outputDocument.Save(String.Format("{0} - Page {1}_tempfile.pdf", name, idx + 1)); } }
public Pdf GeneratePdf(FormData formData) { string text = "first name: " + formData.FirstName + Environment.NewLine + Environment.NewLine + "last name: " + formData.LastName + Environment.NewLine + Environment.NewLine + "comments: " + formData.Comments + Environment.NewLine; PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Times New Roman", 10, XFontStyle.Bold); XTextFormatter tf = new XTextFormatter(gfx); XRect rect = new XRect(40, 100, 250, 220); gfx.DrawRectangle(XBrushes.SeaShell, rect); tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft); document.Save("myDocument.pdf"); return(new Pdf("myDocument.pdf")); }
private void btPDF_Click(object sender, EventArgs e) { PdfDocument pdfDoc = new PdfDocument(); pdfDoc.Info.Title = "Résultats du tri " + triEffectue; PdfPage pDocPage = pdfDoc.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(pDocPage); XFont fontTitle = new XFont("Verdana", 30, XFontStyle.Bold); XFont font = new XFont("Verdana", 20, XFontStyle.Regular); gfx.DrawString("Résultats du tri " + triEffectue, fontTitle, XBrushes.Black, new XRect(0, 0, pDocPage.Width, pDocPage.Height), XStringFormats.TopLeft); int y = 40; foreach (String line in tbConsult.Lines) { gfx.DrawString(line, font, XBrushes.Black, new XRect(0, y, pDocPage.Width, pDocPage.Height), XStringFormats.TopLeft); y += 30; } pdfDoc.Save(@"Resultats_Meilleurs_Jeux " + triEffectue + ".pdf"); }
public static void PdfGenerate(string txt, DateTime emision, int idFact) { //Creamos el pdf PdfDocument pdfDocument = new PdfDocument(); pdfDocument.Info.Title = $"Factura{emision.ToString("yyyyMMdd")}"; //creamos una pag vacia PdfPage page = pdfDocument.AddPage(); //Creamos un objeto para dibujar XGraphics graphics = XGraphics.FromPdfPage(page); //Creamos una fuente XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); //Introducimos el texto graphics.DrawString(txt, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Width), XStringFormats.Center); //Guardamos el documento string filename = $"Factura{idFact}{emision.ToString("yyyyMMdd")}.pdf"; string path = "wwwroot/Pdf/" + filename; pdfDocument.Save(path); }
public IActionResult GeneratePdf() { PdfDocument document = new PdfDocument(); document.Info.Title = "Created with PDFSharp"; PdfPage page = document.AddPage(); XGraphics grf = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); grf.DrawString("Hello World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormat.Center); MemoryStream stream = new MemoryStream(); document.Save(stream, false); stream.Position = 0; return(File(stream, "application/pdf", "HelloPDF.pdf")); }
public void CriaPdfEvidencia(string testCase, string Ambiente = "") { var doc = new PdfDocument(); var page = doc.AddPage(); var gfx = XGraphics.FromPdfPage(page); //Cria Diretorio //Util.CriaDiretorioEvidencias(); //Configura o arquivo Pdf string fileName = ConfiguraArquivo(ScreenShotFields.TestName + ScreenShotFields.Token).ToString(); //Inclui Cabeçalho IncluirCabecalho(gfx, testCase, page, doc, Ambiente); //Captura a tela e inclui no arquivo IncluirImagemPdf(gfx, doc, testCase, page);//.ToString(); //Salva o arquivo SalvarPdf(fileName, doc); gfx.Dispose(); }
public MemoryStream generatePDFInMemory() { // Create PDF document and assign a page to it PdfDocument doc = new PdfDocument(); PdfPage page = doc.AddPage(); //Create graphic object for drawing string and images XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Arial", 10); gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), #pragma warning disable CS0618 // Type or member is obsolete XStringFormat.Center); #pragma warning restore CS0618 // Type or member is obsolete // Save doc on memory stream so that PDF can be generated on the fly MemoryStream ms = new MemoryStream(); doc.Save(ms, true); MemoryStream pdfStream = new MemoryStream(ms.ToArray()); return(pdfStream); }
private PdfDocument ConcatenatePdfs(List <byte[]> documentsToConcatenate) { var outputDocument = new PdfDocument(); foreach (var file in documentsToConcatenate) { using (var stream = new MemoryStream(file)) { var inputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Import); int pageCount = inputDocument.PageCount; for (int i = 0; i < pageCount; i++) { var page = inputDocument.Pages[i]; outputDocument.AddPage(page); } inputDocument.Close(); } } return(outputDocument); }
private static void buildTestDocument(PdfDocument pdf) { PdfFont times = pdf.AddFont(PdfBuiltInFont.HelveticaBoldOblique); double pageWidth = pdf.GetPage(0).Width; PdfPage page = pdf.GetPage(0); for (int i = 0; i < 10; i++) { if (i > 0) { page = pdf.AddPage(); } page.Canvas.Font = times; page.Canvas.FontSize = 16; string titleFormat = string.Format("Page {0}", i + 1); double textWidth = page.Canvas.GetTextWidth(titleFormat); page.Canvas.DrawString(new PdfPoint((pageWidth - textWidth) / 2, 100), titleFormat); } }
/// <summary> /// Combines several image files into a single PDF file. Images will be appended in lexicographical order. /// </summary> /// <param name="directory">The directory used to find files and creating output.</param> /// <param name="outputFile">The name of the output file.</param> public static void AppendImages(string directory, string outputFile) { var files = Directory.GetFiles(directory).Where(filename => Regex.IsMatch(filename, @"\.(jpg|jpeg|png)$")).ToArray(); Array.Sort(files); using (var document = new PdfDocument()) { foreach (var file in files) { var page = new PdfPage(); document.AddPage(page); var graphics = XGraphics.FromPdfPage(page); var image = XImage.FromFile(file); graphics.DrawImage(image, 0, 0, page.Width, page.Height); } var outputPath = Path.Combine(directory, outputFile).UpdateOutputFilename(); document.Save(outputPath); } }
static void Main(string[] args) { var document = new PdfDocument(); var page = document.AddPage(); var gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page); //var font = new XFont("OpenSans", 20, XFontStyle.Bold); //gfx.DrawString("Hello World!", font, XBrushes.Black, new XRect(20, 20, page.Width, page.Height), XStringFormats.Center); //document.Save("test.pdf"); //using (var memoryStream = new FileStream("test.pdf", FileMode.Open)) //{ var readerDco = PdfReader.Open("test.pdf", PdfDocumentOpenMode.Import); Console.WriteLine("Hello World!"); //} Console.WriteLine("Hello World!"); }
void OnExtractPages(object o, EventArgs args) { var to_doc = new PdfDocument(); var from_doc = PdfSharp.Pdf.IO.PdfReader.Open(new Uri(app.Document.CurrentStateUri).LocalPath, PdfDocumentOpenMode.Import, null); var pages = app.IconView.SelectedPages.ToList(); foreach (var index in pages.Select(p => p.Index)) { to_doc.AddPage(from_doc.Pages[index]); } var path = Client.GetTmpFilename(); to_doc.Save(path); to_doc.Dispose(); app.LoadPath(path, Path.Combine( Path.GetDirectoryName(app.Document.SuggestedSavePath), Hyena.StringUtil.EscapeFilename(String.Format("{0} [{1}].pdf", Path.GetFileNameWithoutExtension(app.Document.SuggestedSavePath), GLib.Markup.EscapeText(Document.GetPageSummary(pages, 10)))) )); }
public void Render(string outputFileName) { var rng = new Random(); var pagesOfAnswers = Cards.Where(c => c.Type == "White") .Select((x, i) => new { Card = x, Index = i }) .GroupBy(x => x.Index / 24) .Select(g => new PageOfCards(XColors.Black, XColors.White, g.Select(x => x.Card), FontName)) .OrderBy(x => rng.Next()); var pagesOfQuestions = Cards.Where(x => x.Type == "Black") .Select((x, i) => new { Card = x, Index = i }) .GroupBy(x => x.Index / 24) .Select(g => new PageOfCards(XColors.White, XColors.Black, g.Select(x => x.Card), FontName)) .OrderBy(x => rng.Next()); var allPages = pagesOfAnswers.Concat(pagesOfQuestions); var document = new PdfDocument(); foreach (PageOfCards page in allPages) { page.Render(document.AddPage()); } document.Save(outputFileName); }
private void CreatePdfWithTexts(XImage img, string pdfPath, ParticipantEntity participant) { var pdfPage = new PdfPage { Width = img.PointWidth, Height = img.PointHeight }; var document = new PdfDocument(); document.AddPage(pdfPage); var gfx = XGraphics.FromPdfPage(pdfPage); gfx.DrawImage(img, 0, 0); var drawFont = new XFont("Arial", 48); var drawBrush = new XSolidBrush(XColors.Black); var texts = new List <ImageTextModel> { new ImageTextModel(participant.User.FullName, 1400f, 1002f), new ImageTextModel(participant.School, 1100f, 1124f), new ImageTextModel(participant.SchoolCity, 1524f, 1244f), new ImageTextModel(participant.MentoringTeacher, 1706f, 1481f) { Font = new Font("Arial", 35) } }; foreach (var textModel in texts) { gfx.DrawString(textModel.Text, textModel.Font == null ? drawFont : new XFont("Arial", textModel.Font.Size), drawBrush, textModel.X, textModel.Y); } document.Save(pdfPath); gfx.Dispose(); document.Dispose(); }
public static PdfDocument CreateDocument(Ventana ventana) { PdfDocument document = new PdfDocument(); document.Info.Title = ventana.PO + "_" + ventana.Proveedor.NombreCorto + "_" + ventana.NombreCarrier + "_" + ventana.Evento.FechaInicio.ToString("yyyy-MM-dd"); Document doc = new Document(); Section section = doc.AddSection(); CreateHeader(doc); CreatePage(doc, ventana); var pdfRenderer = new DocumentRenderer(doc); pdfRenderer.PrepareDocument(); int pages = pdfRenderer.FormattedDocument.PageCount; for (int i = 1; i <= pages; ++i) { var page = document.AddPage(); PageInfo pageInfo = pdfRenderer.FormattedDocument.GetPageInfo(i); page.Width = pageInfo.Width; page.Height = pageInfo.Height; page.Orientation = pageInfo.Orientation; using (XGraphics gfx = XGraphics.FromPdfPage(page)) { gfx.MUH = PdfFontEncoding.Unicode; gfx.MFEH = PdfFontEmbedding.Default; pdfRenderer.RenderPage(gfx, i); } } return(document); }
public virtual void ColorTest04() { //Create document with 3 colored rectangles in memory. ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = new PdfWriter(baos); writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION); PdfDocument document = new PdfDocument(writer); PdfPage page = document.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); FileStream streamGray = new FileStream(sourceFolder + "BlackWhite.icc", FileMode.Open, FileAccess.Read); FileStream streamRgb = new FileStream(sourceFolder + "CIERGB.icc", FileMode.Open, FileAccess.Read); FileStream streamCmyk = new FileStream(sourceFolder + "USWebUncoated.icc", FileMode.Open, FileAccess.Read); IccBased gray = new IccBased(streamGray, new float[] { 0.5f }); IccBased rgb = new IccBased(streamRgb, new float[] { 1.0f, 0.5f, 0f }); IccBased cmyk = new IccBased(streamCmyk, new float[] { 1.0f, 0.5f, 0f, 0f }); canvas.SetFillColor(gray).Rectangle(50, 500, 50, 50).Fill(); canvas.SetFillColor(rgb).Rectangle(150, 500, 50, 50).Fill(); canvas.SetFillColor(cmyk).Rectangle(250, 500, 50, 50).Fill(); canvas.Release(); document.Close(); //Copies page from created document to new document. //This is not strictly necessary for ICC-based colors paces test, but this is an additional test for copy functionality. byte[] bytes = baos.ToArray(); PdfReader reader = new PdfReader(new MemoryStream(bytes)); document = new PdfDocument(reader); writer = new PdfWriter(destinationFolder + "colorTest04.pdf"); PdfDocument newDocument = new PdfDocument(writer); newDocument.AddPage(document.GetPage(1).CopyTo(newDocument)); newDocument.Close(); document.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "colorTest04.pdf", sourceFolder + "cmp_colorTest04.pdf", destinationFolder, "diff_")); }
public static void GeneratePdf(ref ProgressBar progressBar, string name, ref double time, ref Label label, string fileName) { using (PdfDocument doc = new PdfDocument()) { string folderPath = "PDF\\CUTTED\\QR\\"; DirectoryInfo dirInfo = new DirectoryInfo(folderPath); Stopwatch sw = new Stopwatch(); foreach (var file in dirInfo.GetFiles("*.jpeg")) { PdfPage page_ = null; XImage img = null; XGraphics graphics = null; sw.Start(); try { page_ = doc.AddPage(); img = XImage.FromFile(file.FullName.ToString()); graphics = XGraphics.FromPdfPage(page_); graphics.DrawImage(img, 0, 0, (int)page_.Width, (int)page_.Height); } finally { page_.Close(); img.Dispose(); graphics.Dispose(); progress(progressBar); } sw.Stop(); time -= sw.ElapsedMilliseconds; TimeCalc.MinuteSeconds(time, label); sw.Reset(); } string[] fileNames = fileName.Split(new char[] { '\\' }); doc.Save($"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\\PDF\\{fileNames[fileNames.Length-1]}"); } Cutter.DeleteJpeg(); }
public void SplitPDF(string filepath, string regex) { using (PdfDocument pdf = PdfReader.Open(filepath, PdfDocumentOpenMode.Import)) { PdfDocument neodoc = new PdfDocument(); bool firstrun = true; bool firstsubpage = true; foreach (PdfPage page in pdf.Pages) { neodoc.AddPage(page); if (firstsubpage == true) { if (firstrun != true) { neodoc.Save(Path.GetDirectoryName(filepath) + Path.DirectorySeparatorChar + "SplitPDF_" + System.Guid.NewGuid().ToString() + ".pdf"); neodoc = new PdfDocument(); } else { firstrun = false; } firstsubpage = false; } for (int index = 0; index < page.Contents.Elements.Count; index++) { PdfDictionary.PdfStream stream = page.Contents.Elements.GetDictionary(index).Stream; string outputText = new PDFTextExtractor().ExtractTextFromPDFBytes(stream.Value); Regex reg = new Regex(regex); Match m = reg.Match(outputText); if (m.Success) { firstsubpage = true; } } } } }
private Paragraph _AddTextToCellWithOverFlow(string instring, Cell cell, Unit fontsize) { if (instring.Length < 3) { return(cell.AddParagraph(instring)); } PdfDocument pdfd = new PdfDocument(); PdfPage pg = pdfd.AddPage(); XGraphics oGFX = XGraphics.FromPdfPage(pg); Unit maxWidth = cell.Column.Width - (cell.Column.LeftPadding + cell.Column.RightPadding); Paragraph par; XFont font = new XFont("Times New Roman", fontsize); if (oGFX.MeasureString(instring, font).Width < maxWidth.Value) { par = cell.AddParagraph(instring); } else { int stringlength = instring.Length; for (int i = 0; i < 3; i++) { if (oGFX.MeasureString(instring.Substring(0, stringlength) + '\u2026', font).Width > maxWidth.Value) { stringlength -= (int)Math.Ceiling(instring.Length * Math.Pow(0.5f, i)); } else if (i < 2) { stringlength += (int)Math.Ceiling(instring.Length * Math.Pow(0.5f, i)); } } par = cell.AddParagraph(instring.Substring(0, stringlength) + '\u2026'); } par.Format.Font.Size = fontsize; return(par); }
private PdfPage Add(PdfDocument pdf, IPageContainer container) { // Create A3 page size with Landscape orientation. var pdfPage = pdf.AddPage(); pdfPage.Size = PageSize.A3; pdfPage.Orientation = PageOrientation.Landscape; var dataFlow = _serviceProvider.GetService <IDataFlow>(); var db = (object)container.Data.Properties; var record = (object)container.Data.Record; dataFlow.Bind(container.Template, db, record); dataFlow.Bind(container, db, record); using (XGraphics gfx = XGraphics.FromPdfPage(pdfPage)) { // Calculate x and y page scale factors. double scaleX = pdfPage.Width.Value / container.Template.Width; double scaleY = pdfPage.Height.Value / container.Template.Height; double scale = Math.Min(scaleX, scaleY); // Set scaling function. _scaleToPage = (value) => value * scale; // Draw container template contents to pdf graphics. Fill(gfx, 0, 0, pdfPage.Width.Value / scale, pdfPage.Height.Value / scale, container.Template.Background); // Draw template contents to pdf graphics. Draw(gfx, container.Template, 0.0, 0.0); // Draw page contents to pdf graphics. Draw(gfx, container, 0.0, 0.0); } return(pdfPage); }
private static void BuildTestOutline(PdfDocument pdf) { PdfOutlineItem root = pdf.OutlineRoot; PdfOutlineItem lastParent = null; PdfFont times = pdf.AddFont(PdfBuiltInFont.TimesItalic); double pageWidth = pdf.GetPage(0).Width; PdfPage page = pdf.GetPage(pdf.PageCount - 1); for (int i = 1; i < 30; i++) { if (i > 1) { page = pdf.AddPage(); } page.Canvas.Font = times; page.Canvas.FontSize = 16; string titleFormat = string.Format("Page {0}", i); double textWidth = page.Canvas.GetTextWidth(titleFormat); page.Canvas.DrawString(new PdfPoint((pageWidth - textWidth) / 2, 100), titleFormat); PdfGoToAction action = pdf.CreateGoToPageAction(i - 1, 0); if (i == 1 || i == 10 || i == 20) { lastParent = root.AddChild(titleFormat, action); } else { lastParent.AddChild(titleFormat, action); } } }
public ActionResult Pay(OrderViewModel order) { // create a new pdf document PdfDocument doc = new PdfDocument(); // add a new page to the document PdfPage page = doc.AddPage(); // create a new pdf font PdfFont font = doc.AddFont(PdfStandardFont.Helvetica); font.Size = 20; // create a new text element and add it to the page PdfTextElement text = new PdfTextElement(50, 50, "Date: " + order.OrderDate.ToString(), font); page.Add(text); page.Add(new PdfTextElement(50, 100, "CustomerId:" + order.CustomerId.ToString(), font)); // save pdf document var bytes = doc.Save(); // close pdf document doc.Close(); return new FileContentResult(bytes, "application/pdf"); }