private void DrawLeftString(string text, float fromleftmm, float fromtopmm, float widthmm, float fontsize) { XPdfFontOptions o = new XPdfFontOptions(PdfFontEncoding.Unicode); XFont font1 = new XFont("Times New Roman", fontsize, XFontStyle.Regular, o); gfx.DrawString(text, font1, XBrushes.Black, new XRect(XUnit.FromMillimeter(fromleftmm).Point, XUnit.FromMillimeter(fromtopmm).Point, XUnit.FromMillimeter(widthmm).Point, 5), XStringFormats.TopLeft); }
/// <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); }
public static void GenerateIdentityCard(IdentityDocumentModel vm) { if (vm.MRZ.Length != 3) { throw new ArgumentException("MRZ should have 3 rows for indentity cards, not : " + vm.MRZ.Length); } // Create a new PDF document PdfDocument document = new PdfDocument(); document.Info.Title = "Created with PDFsharp"; // 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("OCR-B 10 BT", 12, XFontStyle.Regular); var width = XUnit.FromMillimeter(85.68); var height = XUnit.FromMillimeter(54.02); var heightMargin = XUnit.FromInch(.25); var widthMargin = XUnit.FromInch(.25); gfx.DrawRectangle(XBrushes.Beige, new XRect(widthMargin, heightMargin, width, height)); XImage image = XImage.FromFile(@"Templates\IndentityCard_bg.jpg"); gfx.DrawImage(image, widthMargin, heightMargin, width, height); // Draw the text gfx.DrawString(vm.MRZ[0], font, XBrushes.Black, new XRect(XUnit.FromMillimeter(4) + widthMargin, XUnit.FromMillimeter(36.4) + heightMargin, XUnit.FromMillimeter(80), 0), XStringFormats.Default); gfx.DrawString(vm.MRZ[1], font, XBrushes.Black, new XRect(XUnit.FromMillimeter(4) + widthMargin, XUnit.FromMillimeter(41) + heightMargin, XUnit.FromMillimeter(80), 0), XStringFormats.Default); gfx.DrawString(vm.MRZ[2], font, XBrushes.Black, new XRect(XUnit.FromMillimeter(4) + widthMargin, XUnit.FromMillimeter(44.5) + heightMargin, XUnit.FromMillimeter(80), 0), XStringFormats.Default); gfx.DrawLine(XPens.Black, 0, XUnit.FromMillimeter(60) + heightMargin, XUnit.FromInch(8.5), XUnit.FromMillimeter(60) + heightMargin); StringBuilder tmpText = new StringBuilder(); tmpText.AppendLine("DocType : " + vm.DocType); tmpText.AppendLine("CountryOfIssue : " + vm.CountryOfIssue); tmpText.AppendLine("SurName : " + vm.SurName); tmpText.AppendLine("GivenNames : " + vm.GivenNames); tmpText.AppendLine("DocumentNum : " + vm.DocumentNum); tmpText.AppendLine("Dob : " + vm.Dob); tmpText.AppendLine("ExpDate : " + vm.ExpDate); tmpText.AppendLine("OptionalOne : " + vm.OptionalOne); tmpText.AppendLine("OptionalTwo : " + vm.OptionalTwo); tmpText.AppendLine("Nationality : " + vm.Nationality); tmpText.AppendLine("Sex : " + vm.Sex); tmpText = tmpText.Replace('<', ' '); tmpText.AppendLine("MRZ : "); tmpText.AppendLine(string.Join("\n", vm.MRZ)); string text = tmpText.ToString(); XFont font2 = new XFont("Times New Roman", 10, XFontStyle.Bold); XTextFormatter tf = new XTextFormatter(gfx); XRect rect = new XRect(widthMargin, XUnit.FromMillimeter(62) + heightMargin, 250, XUnit.FromMillimeter(62) + heightMargin + 220); gfx.DrawRectangle(XBrushes.LightGray, rect); //tf.Alignment = ParagraphAlignment.Left; tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft); // Save the document... //string filename = "IndentityCard_"+DateTime.Now.ToOADate().ToString()+".pdf"; string filename = "IdentityCard.pdf"; document.Save(filename); System.Diagnostics.Process.Start(filename); }
private void DrawLine(float begxmm, float endxmm, float fromtopmm) { XPen pen = new XPen(XColors.Black, 1); pen.LineCap = XLineCap.Round; pen.LineJoin = XLineJoin.Bevel; XPoint[] points = new XPoint[] { new XPoint(XUnit.FromMillimeter(begxmm).Point, XUnit.FromMillimeter(fromtopmm).Point), new XPoint(XUnit.FromMillimeter(endxmm).Point, XUnit.FromMillimeter(fromtopmm).Point) }; gfx.DrawLines(pen, points); }
internal void OnRender() { if (RenderEvent != null) { //IDocumentPaginatorSource source = this.documentViewer.Document; DrawingVisual dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(XUnit.FromMillimeter(210).Point, XUnit.FromMillimeter(297).Point), XGraphicsUnit.Point); try { RenderEvent(gfx); } catch { } dc.Close(); //DrawingGroup dg = dv.Drawing; // Create page content PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); fixedPage.Background = Brushes.GhostWhite; //UIElement visual = dv; // CreateSecondVisual(false); UIElement visual = new DrawingVisualPresenter(dv); FixedPage.SetLeft(visual, 0); FixedPage.SetTop(visual, 0); double pageWidth = XUnit.FromMillimeter(210).Presentation; double pageHeight = XUnit.FromMillimeter(297).Presentation; fixedPage.Width = pageWidth; fixedPage.Height = pageHeight; fixedPage.Children.Add((UIElement)visual); Size size = new Size(pageWidth, pageHeight); fixedPage.Measure(size); fixedPage.Arrange(new Rect(new Point(), size)); fixedPage.UpdateLayout(); ((IAddChild)pageContent).AddChild(fixedPage); FixedDocument fixedDocument = new FixedDocument(); fixedDocument.DocumentPaginator.PageSize = size; fixedDocument.Pages.Add(pageContent); this.documentViewer.Document = fixedDocument; string savedButton = System.Windows.Markup.XamlWriter.Save(fixedDocument); } else { this.documentViewer.Document = null; } //base.OnRender(drawingContext); ////drawingContext.DrawLine(new Pen(Brushes.Green, 10), new Point(10, 10), new Point(100, 150)); //drawingContext.PushTransform(new ScaleTransform(0.75, 0.75)); //XGraphics gfx = XGraphics.FromDrawingContext(drawingContext, new XSize(100, 100), XGraphicsUnit.Millimeter); //if (RenderEvent != null) //{ // try // { // RenderEvent(gfx); // } // catch // { // RenderEvent = null; // } //} //else // Draw(gfx); }
/// <summary> /// Demonstrates serveral bar code types. /// </summary> public override void RenderPage(XGraphics gfx) { XRect rc; base.RenderPage(gfx); Graphics grfx = gfx.Internals.Graphics; Code2of5Interleaved bc25 = new Code2of5Interleaved(); bc25.Text = "123456"; bc25.Size = new XSize(90, 30); //bc25.Direction = BarCodeDirection.RightToLeft; bc25.TextLocation = TextLocation.Above; gfx.DrawBarCode(bc25, XBrushes.DarkBlue, new XPoint(100, 100)); CodeDataMatrix dm = new CodeDataMatrix("test", 26); dm.Size = new XSize(XUnit.FromMillimeter(15), XUnit.FromMillimeter(15)); gfx.DrawMatrixCode(dm, XBrushes.DarkBlue, new XPoint(300, 100)); rc = new XRect(30, 200, XUnit.FromCentimeter(9.3) + XUnit.FromMillimeter(0.5), XUnit.FromMillimeter(6)); gfx.DrawRectangle(new XSolidBrush(XColor.FromArgb(128, XColors.LightSeaGreen)), rc); CodeOmr omr = new CodeOmr(0xF8F5FF3F.ToString(), rc.Size, CodeDirection.LeftToRight); omr.MakerDistance = XUnit.FromMillimeter(3); omr.MakerThickness = XUnit.FromMillimeter(0.5); gfx.DrawBarCode(omr, XBrushes.Black, rc.Center); omr.Direction = CodeDirection.RightToLeft; gfx.DrawBarCode(omr, XBrushes.Black, rc.Center + new XSize(0, 50)); omr.Direction = CodeDirection.RightToLeft; gfx.DrawBarCode(omr, XBrushes.Black, rc.Center + new XSize(0, 50)); omr.Direction = CodeDirection.TopToBottom; gfx.DrawBarCode(omr, XBrushes.Black, rc.Center + new XSize(300, 25)); }
private void RenderGrid(XGraphics gfx) { int x, y; //Create the grid for (x = 0; x < pageSettings.LabelsX; x++) { for (y = 0; y < pageSettings.LabelsY; y++) { XSize sSize = new XSize(XUnit.FromMillimeter(pageSettings.Spacing.Width), XUnit.FromMillimeter(pageSettings.Spacing.Height)); XSize lSize = new XSize(XUnit.FromMillimeter(pageSettings.LabelSize.Width), XUnit.FromMillimeter(pageSettings.LabelSize.Height)); XPoint lPt = new XPoint(XUnit.FromMillimeter(pageSettings.FirstLabel.X), XUnit.FromMillimeter(pageSettings.FirstLabel.Y)); XPoint pt = new XPoint(x * (lSize.Width + sSize.Width) + lPt.X, y * (lSize.Height + sSize.Height) + lPt.Y); //Just draw each side for all labels, dont care if they overlap... XRect rect = new XRect(pt, lSize); gfx.DrawRoundedRectangle(XPens.Black, rect, new XSize(XUnit.FromMillimeter(pageSettings.Corner.Width), XUnit.FromMillimeter(pageSettings.Corner.Height))); //foreach (LabelItem item in labelItems) // item.Render(gfx, pt); } } }
// This sample shows how to create an XForm object from scratch. You can think of such an // object as a template, that, once created, can be drawn frequently anywhere in your PDF document. protected override void DoWork() { // 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("AltData/PDFsharp/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("AltData/PDFsharp/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. Diagnostics.ProcessHelper.Start(filename); }
/// <summary> /// This method will print the Article detail table with appropriate /// column header according to the template /// </summary> /// <param name="colwidth">different column width</param> /// <param name="form">Supplied XForm</param> /// <param name="dtArticle">supplied datatable containing article information</param> private void PrintArticleDetail(double[] colwidth, ref XForm form, DataTable dtArticle) { XGraphics graphics = XGraphics.FromForm(form); XTextFormatter tf = new XTextFormatter(graphics); XTextFormatter tf1 = new XTextFormatter(graphics); XRect rec; int pagecounter = 0; double left = 0, top = 0; // Print header for (int index = 0; index < colwidth.Length; index++) { rec = new XRect(left, top, colwidth[index], 19); /*if (index % 2 == 0) * { * graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), rec); * } * else * {*/ graphics.DrawRectangle(XBrushes.Gray, rec); //} string header = dtArticle.Columns[index].ColumnName; int count = header.Length; if (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(header.PadLeft(count + 3), report._smallFontBold, XBrushes.White, rec); } else { tf.Alignment = XParagraphAlignment.Center; tf.DrawString(header.PadRight(count + 3), report._smallFontBold, XBrushes.White, rec); } left += colwidth[index]; } //print Articles foreach (DataRow row in dtArticle.Rows) { pagecounter++; top += 20; left = 0; if (pagecounter % 15 == 0) { //top = -500; //report.document.AddPage(); report.gfx.DrawImage(form, 28, 350); top = 0; PdfPage page = new PdfPage(); page = report.document.Pages.Add(); report.gfx = XGraphics.FromPdfPage(page); form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); tf = new XTextFormatter(graphics); tf1 = new XTextFormatter(graphics); //Print Invoice XForm form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); XGraphics graphics1 = XGraphics.FromForm(form1); double xInit = 0, yInit = 0; graphics1.DrawString(CulturalValues[0], report._largeFontBold, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 450, 40); // Print Customer Address form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); xInit = 95; yInit = 20; //graphics.DrawRectangle(report._borderPen, 0, 0, 300, 100); graphics1.DrawString(dthead1.Rows[0]["companyname"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit - report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["customer"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["address"].ToString() + " " + dthead1.Rows[0]["housenr"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["postcode"].ToString() + " " + dthead1.Rows[0]["residence"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 2, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["country"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 3, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 245, 130); // Print Our VAT No + Bankaccount details form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); xInit = 5; yInit = 5; graphics1.DrawRectangle(XBrushes.Gray, 0, 0, 300, 20); graphics1.DrawString(CulturalValues[1], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics1.DrawString(CulturalValues[2], report._smallFont, XBrushes.White, xInit + 120, yInit, XStringFormat.TopLeft); graphics1.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, xInit + 115, 60); graphics1.DrawString("NL006012152B01", report._smallFontBold, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics1.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), xInit + 115, 20, 180, 60); graphics1.DrawString("ABNAMRO:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString("61 26 26 032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString("IBAN:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString("NL08ABNA0612626032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString("BIC:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics1.DrawString("ABNANL2A", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 28, 260); //print For payment please quote form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); xInit = 5; yInit = 5; graphics1.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics1.DrawString(CulturalValues[3], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics1.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, 230, 60); graphics1.DrawString(CulturalValues[4], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["customerid"].ToString().Trim(), report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString(CulturalValues[5], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(iid, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(CulturalValues[6], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); string s = dthead1.Rows[0]["invoicedate"].ToString(); graphics1.DrawString(s, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics1.DrawRectangle(report._borderPen, 0, 0, 230, 80); report.gfx.DrawImage(form1, 333, 260); form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); string Show_page = "Page " + pagenumber + " of " + totalpage + " (" + iid + ")."; pagenumber += 1; //graphics.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics1.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 90, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 28, 710); for (int index = 0; index < colwidth.Length; index++) { rec = new XRect(left, top, colwidth[index], 19); /*if (index % 2 == 0) * { * graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), rec); * } * else * {*/ graphics.DrawRectangle(XBrushes.Gray, rec); //} string header = dtArticle.Columns[index].ColumnName; int count = header.Length; if (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(header.PadLeft(count + 3), report._smallFontBold, XBrushes.White, rec); } else { tf.Alignment = XParagraphAlignment.Center; tf.DrawString(header.PadRight(count + 3), report._smallFontBold, XBrushes.White, rec); } left += colwidth[index]; } left = 0; top += 20; //rec; //report.document.AddPage(page); //report.gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append); } for (int index = 0; index < colwidth.Length; index++) { //tf.Alignment = (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) ? XParagraphAlignment.Left : XParagraphAlignment.Right; rec = new XRect(left, top, colwidth[index], 20); XRect rec1 = new XRect(left + 5, top, colwidth[index], 20); if (index % 2 == 0) { graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), rec); } else { graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(60, 204, 204, 204)), rec); } int count = row[index].ToString().Length; if (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) { tf.Alignment = XParagraphAlignment.Left; //tf1.Alignment = XParagraphAlignment.Right; if (dtArticle.Columns[index].ToString().Equals(CulturalValues[19])) { tf.DrawString(row[index].ToString().PadLeft(count + 3), report._smallFont, XBrushes.Black, rec); } if (dtArticle.Columns[index].ToString().Equals(CulturalValues[20])) { if (row[index].ToString().Trim().Equals("Shipping and handling")) { if (CulturalValues[27] == "nl-NL") { tf.DrawString("Verzendkosten".ToString(), report._smallFont, XBrushes.Black, rec1); } else { tf.DrawString("Shipping and handling".ToString(), report._smallFont, XBrushes.Black, rec1); } } else { tf.DrawString(row[index].ToString() + " - " + row["Composer"].ToString(), report._smallFont, XBrushes.Black, rec1); } } } else { tf.Alignment = XParagraphAlignment.Right; tf.DrawString(row[index].ToString().PadRight(count + 3), report._smallFont, XBrushes.Black, rec); if (dtArticle.Columns[index].ToString().Equals(CulturalValues[22]) || dtArticle.Columns[index].ToString().Equals(CulturalValues[24])) { tf.DrawString("€".PadRight(22), report._smallFont, XBrushes.Black, rec); } } //tf.DrawString(row[index].ToString(), report._smallFont, XBrushes.Black, rec); left += colwidth[index]; } } }
private void RenderLabel(XGraphics gfx) { XSize lSize = new XSize(XUnit.FromMillimeter(pageSettings.LabelSize.Width), XUnit.FromMillimeter(pageSettings.LabelSize.Height)); XPoint lPt = new XPoint(0, 0); //Just draw each side for all labels, dont care if they overlap... XRect rect = new XRect(lPt, lSize); gfx.DrawRoundedRectangle(XPens.Black, rect, new XSize(XUnit.FromMillimeter(pageSettings.Corner.Width), XUnit.FromMillimeter(pageSettings.Corner.Height))); foreach (LabelItem item in labelItems) { item.Render(gfx, lPt); } }
/// <summary> /// This method will Generate the invoice as a pdf file. /// </summary> /// <param name="dtBody">this datatable will contain all article information in the invoice</param> /// <param name="dtHead">this datatable will contain all information related to this invoice</param> /// <param name="dtVat">this datatable will contain all types of VAT summary exist in the invoice</param> /// <param name="invoiceId">Supplied invoiceid</param> private void ReportGenerator(DataTable dtBody, DataTable dtHead, DataTable dtVat, string invoiceId, DataTable dtPrice) { Double totalShippingCost = 0.00; Double totalVat = 0.00; Double subTotal = 0.00; Double invoiceTotal = 0.00; for (int i = 0; i < dtBody.Rows.Count; i++) { subTotal += Double.Parse(dtBody.Rows[i][5].ToString());// +Double.Parse(dtBody.Rows[i][8].ToString()); totalVat += Double.Parse(dtBody.Rows[i][8].ToString()); } string sql = "select sum(o.shippingcost) as total from orders o" + " where o.orderid in(select orderid from invoiceline where invoiceid='" + invoiceId + "')"; DataTable dtShipCost = dbHandler.GetDataTable(sql); totalShippingCost = Double.Parse(dtShipCost.Rows[0]["total"].ToString()); if (!dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) { invoiceTotal = subTotal;// +totalShippingCost; //invoiceTotal = subTotal + totalShippingCost; } else { invoiceTotal = subTotal + totalVat; } //Print Invoice XForm form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); XGraphics graphics = XGraphics.FromForm(form); double xInit = 0, yInit = 0; graphics.DrawString(CulturalValues[0], report._largeFontBold, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); report.gfx.DrawImage(form, 390, 40); // Print Customer Address dthead1 = dtHead; form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 95; yInit = 20; //graphics.DrawRectangle(report._borderPen, 0, 0, 300, 100); graphics.DrawString(dtHead.Rows[0]["companyname"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit - report._lineGap, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["customer"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["address"].ToString() + " " + dtHead.Rows[0]["housenr"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["postcode"].ToString() + " " + dtHead.Rows[0]["residence"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 2, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["country"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 3, XStringFormat.TopLeft); report.gfx.DrawImage(form, 245, 130); // Print Our VAT No + Bankaccount details form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 5; yInit = 5; graphics.DrawRectangle(XBrushes.Gray, 0, 0, 300, 20); graphics.DrawString(CulturalValues[1], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[2], report._smallFont, XBrushes.White, xInit + 120, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, xInit + 115, 60); graphics.DrawString("NL006012152B01", report._smallFontBold, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), xInit + 115, 20, 180, 60); graphics.DrawString("ABNAMRO:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25, XStringFormat.TopLeft); graphics.DrawString("61 26 26 032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25, XStringFormat.TopLeft); graphics.DrawString("IBAN:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString("NL08ABNA0612626032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString("BIC:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics.DrawString("ABNANL2A", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); report.gfx.DrawImage(form, 28, 260); //print For payment please quote iid = invoiceId; form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 5; yInit = 5; graphics.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics.DrawString(CulturalValues[3], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, 230, 60); graphics.DrawString(CulturalValues[4], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["customerid"].ToString().Trim(), report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[5], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(invoiceId, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[6], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); string s = dtHead.Rows[0]["invoicedate"].ToString(); graphics.DrawString(s, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics.DrawRectangle(report._borderPen, 0, 0, 230, 80); report.gfx.DrawImage(form, 333, 260); //VAT basis + VAT amount form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 5; yInit = 5; double seg_width = 70; XTextFormatter tf = new XTextFormatter(graphics); graphics.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics.DrawString(CulturalValues[7], report._smallFont, XBrushes.White, 98, yInit, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[8], report._smallFont, XBrushes.White, 180, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, seg_width, 60); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), seg_width, 20, seg_width, 60); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), seg_width * 2, 20, 90, 60); graphics.DrawString(CulturalValues[9], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); XRect rec = new XRect(seg_width, yInit + 25, 65, 20); tf.Alignment = XParagraphAlignment.Right; if (!dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) { Double vatBasis = double.Parse(dtPrice.Rows[0]["price0"].ToString()) + double.Parse(dtPrice.Rows[0]["price6"].ToString()) + double.Parse(dtPrice.Rows[0]["price19"].ToString()); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(vatBasis.ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[10], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[11], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap * 2, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap * 2, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[12], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["customerbtwnr"].ToString(), report._smallFont, XBrushes.Black, 100, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); } else { tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtPrice.Rows[0]["price0"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtVat.Rows[0]["vat0"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[10], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtPrice.Rows[0]["price6"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtVat.Rows[0]["vat6"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[11], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap * 2, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtPrice.Rows[0]["price19"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap * 2, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtVat.Rows[0]["vat19"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); //graphics.DrawString(CulturalValues[12], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); //graphics.DrawString(dtHead.Rows[0]["customerbtwnr"].ToString(), report._smallFont, XBrushes.Black, 100, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); } //report.gfx.DrawImage(form, 28, 720); //Page Number //string Show_page = "Page "+ s +" of "+seg_width +"."; totalpage = dtPage.Rows[0]["page"].ToString(); if (Convert.ToInt32(totalpage) >= 1) { pagenumber = 1; } string Show_page = "Page " + pagenumber + " of " + totalpage + " (" + invoiceId + ")."; pagenumber += 1; //graphics.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 90, XStringFormat.TopLeft); report.gfx.DrawImage(form, 28, 710); //if (dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) //Sub Total form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); tf = new XTextFormatter(graphics); tf.Alignment = XParagraphAlignment.Right; xInit = 5; yInit = 5; graphics.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics.DrawString(CulturalValues[13], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), 100, 20, 130, 60); graphics.DrawString(CulturalValues[14], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[26], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); //graphics.DrawString("VAT: ", report._smallFontBold, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[16], report._smallFontBold, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); rec = new XRect(100, yInit + 25, 100, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(subTotal.ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(100, yInit + 25 + report._lineGap, 100, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); if (!dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) { tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); } else { tf.DrawString(totalVat.ToString("N2"), report._smallFont, XBrushes.Black, rec); } rec = new XRect(100, yInit + 25 + report._lineGap * 2, 100, 20); tf.DrawString("€".PadRight(25), report._smallFontBold, XBrushes.Black, rec); tf.DrawString(invoiceTotal.ToString("N2"), report._smallFontBold, XBrushes.Black, rec); graphics.DrawString(CulturalValues[17], report._verySmallFont, XBrushes.Black, 115, yInit + 25 + report._lineGap * 3, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[18], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US", true); System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo(); dtfi.ShortDatePattern = "dd-MM-yyyy"; dtfi.DateSeparator = "-"; DateTime dtIn = Convert.ToDateTime(s, dtfi); dtIn = dtIn.AddDays(14); graphics.DrawString(dtIn.ToString("dd-MM-yyyy"), report._smallFont, XBrushes.Black, 115, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics.DrawRectangle(report._borderPen, 0, 0, 230, 80); report.gfx.DrawImage(form, 333, 710); //Populate Article Details double[] colWidth = { 50, 220, 40, 60, 55, 60, 50 }; //string[] colName = {"Article ID", "Description", "Quantity", "Retail Price", "Discount", "Net Price", "VAT" }; form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); PrintArticleDetail(colWidth, ref form, dtBody); report.gfx.DrawImage(form, 28, 350); }
/// <summary> /// Generates the pdf document containing the specified stickers. No specs of the sheet are /// provided with the system. It should be a good idea. /// </summary> /// <param name="pdfPath">The full path to the pdf folder.</param> /// <param name="numberOfStickersLeftInSheet">The number of stickers left on the sheet used.</param> /// <param name="stickers">The stickers to layout in the document.</param> /// <returns></returns> public static string GeneratePreview( string pdfPath, int numberOfStickersLeftInSheet, IEnumerable <StickerInfo> stickers) { var numberOfBlanks = MAX_NUMBER_OF_STICKERS_PER_SHEET - numberOfStickersLeftInSheet; var numberOfStickersLeft = stickers.Count(); var document = new PdfDocument(); var page = document.AddPage(); var gtx = XGraphics.FromPdfPage(page); var nbFormatInfo = new CultureInfo("fr-CA", false).NumberFormat; var firstLeftRect = new XRect( XUnit.FromCentimeter(0), XUnit.FromCentimeter(1.9), XUnit.FromCentimeter(10.2), XUnit.FromCentimeter(3.4) ); page.Size = PdfSharp.PageSize.Letter; page.TrimMargins = new TrimMargins() { Left = XUnit.FromMillimeter(4), Top = XUnit.FromCentimeter(2) + XUnit.FromMillimeter(1), Right = XUnit.FromMillimeter(4), Bottom = XUnit.FromCentimeter(2) + XUnit.FromMillimeter(1) }; // O(n^2) for (int currentColumn = 0; currentColumn < NUMBER_OF_COLUMNS && numberOfStickersLeft > 0; currentColumn++) { var currentXPos = currentColumn * (firstLeftRect.Width + XUnit.FromMillimeter(9)); for (int position = 0; position < MAX_NUMBER_OF_STICKERS_PER_COLUMN && numberOfStickersLeft > 0; position++) { if (numberOfBlanks == 0) { var sticker = stickers.ElementAt(stickers.Count() - numberOfStickersLeft); var LivrETSID = $"{sticker.FairLivrETSID}-{sticker.UserLivrETSID}-{sticker.ArticleLivrETSID}"; var barcode = GenerateLivrETSBarCode(LivrETSID); var padding = XUnit.FromMillimeter(2); var currentYPos = (firstLeftRect.Height + XUnit.FromMillimeter(2.5)) * position; var currentRect = new XRect( currentXPos, currentYPos, firstLeftRect.Width, firstLeftRect.Height ); var fairTextRect = new XRect( currentRect.Left + padding, currentRect.Top + padding, currentRect.Width / 2, XUnit.FromMillimeter(5) ); var livretsIdRect = new XRect( currentRect.Left, currentRect.Bottom - XUnit.FromMillimeter(4), currentRect.Width, XUnit.FromMillimeter(4) ); var barCodeRect = new XRect( currentRect.Left + padding, livretsIdRect.Top - XUnit.FromMillimeter(6.2), currentRect.Width - 2 * padding, XUnit.FromMillimeter(6) ); var priceRect = new XRect( fairTextRect.Right, currentRect.Top + padding, currentRect.Width / 2, fairTextRect.Height ); var titleRect = new XRect( currentRect.Left + padding, fairTextRect.Bottom, currentRect.Width - 2 * padding, barCodeRect.Top - fairTextRect.Bottom ); gtx.DrawString( $"Foire {sticker.FairLivrETSID}", new XFont("Arial", 8, XFontStyle.Regular), XBrushes.Black, fairTextRect, XStringFormats.TopLeft ); gtx.DrawString( sticker.OfferPrice.ToString("C", nbFormatInfo), new XFont("Arial", 12, XFontStyle.Regular), XBrushes.Black, priceRect, XStringFormats.TopLeft ); gtx.DrawString( sticker.ArticleTitle, new XFont("Arial", 10, XFontStyle.Regular), XBrushes.Black, titleRect, XStringFormats.TopLeft ); gtx.DrawImage( XImage.FromGdiPlusImage(barcode), barCodeRect ); gtx.DrawString( LivrETSID, new XFont("Arial", 9, XFontStyle.Regular), XBrushes.Black, livretsIdRect, XStringFormats.TopCenter ); numberOfStickersLeft--; } else { numberOfBlanks--; } } } return(FileSystemFacade.SaveStickersDocument(document, pdfPath)); }
/// <summary> /// Generates a Code 39 bar code from the complete LivrETSID from TRIBSTD01-2016 /// </summary> /// <param name="LivrETSID">See TRIBSTD01-2016 for how to construct the Id.</param> /// <returns>An image of the barcode.</returns> private static Image GenerateLivrETSBarCode(string LivrETSID) { Code93BarcodeDraw barCodeDrawer = BarcodeDrawFactory.Code93WithChecksum; return(barCodeDrawer.Draw(LivrETSID, maxBarHeight: (int)XUnit.FromMillimeter(6))); }
// draws a single Paper Wallet in to a PdfSharp XForm private PdfSharp.Drawing.XForm getSingleWallet(PdfDocument doc, WalletBundle b, XImage imgArtwork, string address, string privkey, int numberWithinBatch, bool layoutDebugging) { WalletTemplate t = b.template; double width = t.widthMM; double height = t.heightMM; XUnit walletSizeWide = XUnit.FromMillimeter(width); XUnit walletSizeHigh = XUnit.FromMillimeter(height); PdfSharp.Drawing.XForm form = new PdfSharp.Drawing.XForm(doc, walletSizeWide, walletSizeHigh); using (XGraphics formGfx = XGraphics.FromForm(form)) { XGraphicsState state = formGfx.Save(); bool interpolateArtwork = true; bool interpolateQRcodes = false; // XImage imgArtwork is now provided by caller, so this process only has to be done ONCE - because the artwork does not change between Wallets in a run! //XImage imgArtwork = XImage.FromGdiPlusImage(b.getArtworkImage()); imgArtwork.Interpolate = interpolateArtwork; formGfx.DrawImage(imgArtwork, new RectangleF(0f, 0f, (float)walletSizeWide.Point, (float)walletSizeHigh.Point)); // draw the QR codes and legible-text things // Address // QR Bitmap bmpAddress = BtcAddress.QR.EncodeQRCode(address); XImage imgAddress = XImage.FromGdiPlusImage(bmpAddress); imgAddress.Interpolate = interpolateQRcodes; XUnit addressQrLeft = XUnit.FromMillimeter(t.addressQrLeftMM); XUnit addressQrTop = XUnit.FromMillimeter(t.addressQrTopMM); XUnit addressQrSize = XUnit.FromMillimeter(t.addressQrSizeMM); // only print Address QR if called for if (t.addressQrSizeMM > 0.1) { XRect addressQrRect = new XRect(addressQrLeft.Point, addressQrTop.Point, addressQrSize.Point, addressQrSize.Point); formGfx.DrawImage(imgAddress, addressQrRect); } // text address string addressSplitForLines = addressOrReferencePrep(address, t.addressTextCharsPerLine, t.addressTextContentVariant, numberWithinBatch); XFont fontAddress = new XFont(t.addressTextFontName, t.addressTextFontSize, t.addressTextFontStyle); XTextFormatter tf = new XTextFormatter(formGfx); XUnit addressTxtLeft = XUnit.FromMillimeter(t.addressTextLeftMM); XUnit addressTxtTop = XUnit.FromMillimeter(t.addressTextTopMM); XUnit addressTxtWidth = XUnit.FromMillimeter(t.addressTextWidthMM); XUnit addressTxtHeight = XUnit.FromMillimeter(t.addressTextHeightMM); XRect addressRect = new XRect(addressTxtLeft.Point, addressTxtTop.Point, addressTxtWidth.Point, addressTxtHeight.Point); tf.Alignment = XParagraphAlignment.Center; TextRotation addressTxtRotation = t.addressTextRotation; double addressTxtRotationDegrees = RotationMarkerToDegrees(addressTxtRotation); if (layoutDebugging) { formGfx.DrawRectangle(XBrushes.PowderBlue, addressRect); } XPoint rotateCentre = new XPoint(addressTxtLeft + (addressTxtWidth / 2), addressTxtTop + (addressTxtHeight / 2)); XPoint matrixRotatePoint = new XPoint(addressRect.X + (addressRect.Width / 2), addressRect.Y + (addressRect.Height / 2)); XMatrix rotateMatrix = new XMatrix(); rotateMatrix.RotateAtAppend(addressTxtRotationDegrees, rotateCentre); addressRect.Transform(rotateMatrix); if (layoutDebugging) { // draw a little tracer dot for where the centre of rotation is going to be double rotateDotSize = 2.0; formGfx.DrawEllipse(XBrushes.Red, rotateCentre.X - (rotateDotSize / 2), rotateCentre.Y - (rotateDotSize / 2), rotateDotSize, rotateDotSize); } // maybe even do some rotation of the lovely text! formGfx.Save(); formGfx.RotateAtTransform(addressTxtRotationDegrees, rotateCentre); if (layoutDebugging) { formGfx.DrawRectangle(XPens.OrangeRed, addressRect); } if (t.addressTextWidthMM > 0.1) { tf.DrawString(addressSplitForLines, fontAddress, t.GetBrushAddress, addressRect); } formGfx.Restore(); // Privkey // QR Bitmap bmpPrivkey = BtcAddress.QR.EncodeQRCode(privkey); XImage imgPrivkey = XImage.FromGdiPlusImage(bmpPrivkey); imgPrivkey.Interpolate = interpolateQRcodes; XUnit privkeyQrLeft = XUnit.FromMillimeter(t.privkeyQrLeftMM); XUnit privkeyQrTop = XUnit.FromMillimeter(t.privkeyQrTopMM); XUnit privkeyQrSize = XUnit.FromMillimeter(t.privkeyQrSizeMM); XRect privkeyQrRect = new XRect(privkeyQrLeft.Point, privkeyQrTop.Point, privkeyQrSize.Point, privkeyQrSize.Point); // only print privkey QR if specified - but you'd have to be an UTTER IDIOT to want to exclude this. Still, user input comes first! if (t.privkeyQrSizeMM > 0.1) { formGfx.DrawImage(imgPrivkey, privkeyQrRect); } // legible string privkeySplitForLines = lineSplitter(privkey, t.privkeyTextCharsPerLine); XFont fontPrivkey = new XFont(t.privkeyTextFontName, t.privkeyTextFontSize, t.privkeyTextFontStyle); XUnit privkeyTxtLeft = XUnit.FromMillimeter(t.privkeyTextLeftMM); XUnit privkeyTxtTop = XUnit.FromMillimeter(t.privkeyTextTopMM); XUnit privkeyTxtWidth = XUnit.FromMillimeter(t.privkeyTextWidthMM); XUnit privkeyTxtHeight = XUnit.FromMillimeter(t.privkeyTextHeightMM); TextRotation privkeyTxtRotation = t.privkeyTextRotation; double privkeyTxtRotationDegrees = RotationMarkerToDegrees(privkeyTxtRotation); XRect privkeyRect = new XRect(privkeyTxtLeft.Point, privkeyTxtTop.Point, privkeyTxtWidth.Point, privkeyTxtHeight.Point); if (layoutDebugging) { // draw a tracer rectangle for the original un-rotated text rectangle formGfx.DrawRectangle(XBrushes.PowderBlue, privkeyRect); } // rotate that lovely text around its middle when drawing! rotateCentre = new XPoint(privkeyTxtLeft + (privkeyTxtWidth / 2), privkeyTxtTop + (privkeyTxtHeight / 2)); matrixRotatePoint = new XPoint(privkeyRect.X + (privkeyRect.Width / 2), privkeyRect.Y + (privkeyRect.Height / 2)); rotateMatrix = new XMatrix(); rotateMatrix.RotateAtAppend(privkeyTxtRotationDegrees, rotateCentre); privkeyRect.Transform(rotateMatrix); if (layoutDebugging) { // draw a little tracer dot for where the centre of rotation is going to be double rotateDotSize = 2.0; formGfx.DrawEllipse(XBrushes.Red, rotateCentre.X - (rotateDotSize / 2), rotateCentre.Y - (rotateDotSize / 2), rotateDotSize, rotateDotSize); } formGfx.Save(); formGfx.RotateAtTransform(privkeyTxtRotationDegrees, rotateCentre); if (layoutDebugging) { formGfx.DrawRectangle(XPens.OrangeRed, privkeyRect); } // only print privkey text if specified. if (t.privkeyTextWidthMM > 0.1) { tf.DrawString(privkeySplitForLines, fontPrivkey, t.GetBrushPrivkey, privkeyRect); } formGfx.Restore(); } return(form); }
private void TabControl1_SelectedIndexChanged(object sender, EventArgs e) { switch (tabControl1.SelectedIndex) { case 0: pagePreview1.PageSize = PageSizeConverter.ToSize(pageSettings.PageSize); propertyGrid1.SelectedObject = null; RefreshTable(); break; case 1: pagePreview1.PageSize = new XSize(XUnit.FromMillimeter(pageSettings.LabelSize.Width), XUnit.FromMillimeter(pageSettings.LabelSize.Height)); break; case 2: pagePreview1.PageSize = PageSizeConverter.ToSize(pageSettings.PageSize); break; } pagePreview1.Refresh(); }
private void btnFirstPrototype_Click(object sender, EventArgs e) { int pagecount; if (!int.TryParse(txtNumberPages.Text, out pagecount)) { MessageBox.Show("Number of Pages is required", "Number of Pages is required", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (pagecount < 1 || pagecount > 99) { MessageBox.Show("Number of Pages must be between 1-99", "Invalid Number of Pages", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // todo: take this out of the UI thread, put it in a class and run on a worker thread // and also rename this button - it's been a long time since this was my original prototype string previousCaption = this.Text; btnFirstPrototype.Enabled = false; this.Text = "GENERATING..."; this.UseWaitCursor = true; // todo: move all the grunt work in to a nice proper Threaded situation // meanwhile, DoEvents is called here to allow the wait cursor, form caption and other "I'm busy..." indicators to be shown to the user before we get into the hard stuff that takes a few moments Application.DoEvents(); string outputFile = txtOutputFile.Text; string logFilePath = string.Format("{0} - LOG {1}.txt", outputFile, DateTime.Now.ToString("yyyy-MM-dd HHmmss")); StreamWriter logFile = new StreamWriter(logFilePath); CoinDef thiscoin = new CoinDef(bundle.template.CoinName, bundle.template.CoinAddressType, bundle.template.CoinIsWIFstupid); logFile.WriteLine(string.Format("Paper Wallet Printer version {0}", Application.ProductVersion)); logFile.WriteLine(string.Format("Generating wallets for coin {0}", thiscoin.ToString())); logFile.WriteLine("Using template: " + bundle.template.TemplateDescription.Replace("\n", " ")); // removes any line breaks from template description as it writes it to the log file bundle.template.LayoutDebugging = layoutDebuggingToolStripMenuItem.Checked; if (bundle.template.LayoutDebugging) { logFile.WriteLine("Layout Debugging is enabled - printed wallets are not intended for live use"); } // make a pdfSharp document PdfDocument doc = new PdfDocument(); int batchNumber = 1; bool crashingOut = false; XImage imgArtwork = XImage.FromGdiPlusImage(bundle.getArtworkImage()); // loop for each page for (int pageNumber = 1; pageNumber <= pagecount; pageNumber++) { // and put a page on it PdfPage page = doc.AddPage(); // note: if you change anything that gets written to logFile from this point until the end-marker is written, this will probably cause // compatibility issues with the Loader tool, which expects to be able to parse the log between these points logFile.WriteLine(string.Format("Generating Page {0} of {1}", pageNumber, pagecount)); logFile.WriteLine("Generated Addresses:"); logFile.WriteLine(); page.Size = bundle.template.pagePrintPaperSize; using (XGraphics gfx = XGraphics.FromPdfPage(page, XPageDirection.Downwards)) { // LOOP Down for (int y = 0; y < bundle.template.pagePrintRows; y++) { // LOOP Across for (int x = 0; x < bundle.template.pagePrintCols; x++) { try { // get PrivKey and Address for this new Wallet KeyPair kp = KeyPair.CreateX(ExtraEntropy.GetEntropy(), false, bundle.template.CoinAddressType, bundle.template.CoinIsWIFstupid); KeyCollectionItem item = new KeyCollectionItem(kp); string address = item.GetAddressBase58(); logFile.WriteLine(address); // get an XForm of our Wallet using (XForm walletForm = getSingleWallet(doc, bundle, imgArtwork, address, item.PrivateKey, batchNumber, bundle.template.LayoutDebugging)) { // decide where on the page to draw this wallet XForm object XUnit walletLeft = XUnit.FromMillimeter(bundle.template.pagePrintLeftMarginMM + ((bundle.template.widthMM + bundle.template.pagePrintColGap) * x)); XUnit walletTop = XUnit.FromMillimeter(bundle.template.pagePrintTopMarginMM + ((bundle.template.heightMM + bundle.template.pagePrintRowGap) * y)); XPoint whereToPutTheForm = new XPoint(walletLeft.Point, walletTop.Point); gfx.DrawImage(walletForm, whereToPutTheForm); } batchNumber++; } catch (Exception ex) { // well, damn... logFile.WriteLine("--- CRASH! ---"); logFile.WriteLine("Encountered Unhandled Exception inside primary Y-X Print Loop"); logFile.WriteLine("Exception:"); logFile.WriteLine(ex.Message); logFile.WriteLine(ex.Source); logFile.WriteLine(ex.StackTrace); crashingOut = true; break; } } if (crashingOut) { break; } } } if (crashingOut) { break; } logFile.WriteLine(); logFile.WriteLine("end"); logFile.WriteLine(); } if (!crashingOut) { logFile.WriteLine("Internal PDF Generation completed OK"); if (File.Exists(outputFile)) { File.Delete(outputFile); } try { doc.Save(outputFile); } catch (Exception ex) { logFile.WriteLine("--- CRASH! ---"); logFile.WriteLine("Encountered Unhandled Exception when Saving PDF from Object to File"); logFile.WriteLine("Exception:"); logFile.WriteLine(ex.Message); logFile.WriteLine(ex.Source); logFile.WriteLine(ex.StackTrace); crashingOut = true; } logFile.WriteLine("PDF saved to File OK - all done"); } logFile.Close(); // if we have failed in generating the PDF in to memory, or failed when saving it to file - show an error to the user, directing them to to the log file if (crashingOut) { this.Text = previousCaption; btnFirstPrototype.Enabled = true; this.UseWaitCursor = false; string errmsg = string.Format("Sorry, Wallet Printing has failed. See the log file for details.\n\nLog file:\n{0}", logFilePath); MessageBox.Show(errmsg, "Printing Failed, Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (chkOpenAfterGenerating.Checked) { // note the current datetime, for comparison if we're trying to wait for PDF Viewer DateTime timeOfStartingViewer = DateTime.Now; System.Diagnostics.Process procViewer = System.Diagnostics.Process.Start(outputFile); if (chkWipeOutputAfterViewing.Checked) { btnFirstPrototype.Enabled = false; this.Text = "WAITING FOR PDF VIEWER TO CLOSE"; procViewer.WaitForExit(); // ok, we *think* that maybe their PDF viewer has closed. But that might not be true. // check to see if we were delayed by a Suspiciously Short length of time TimeSpan timeWaitedForViewer = DateTime.Now - timeOfStartingViewer; if (timeWaitedForViewer.TotalSeconds < 15) { MessageBox.Show("I think your PDF viewer closed really quickly - or I cannot detect if you are done with the generated PDF.\n\nPlease click OK when you are ready for me to delete the generated PDF.", "Ready to delete PDF file?", MessageBoxButtons.OK, MessageBoxIcon.Question); } // overwrite contents of PDF with junk, then delete. This won't be secure against serious forensic attack in all situations, but it's better than just-delete FileInfo info = new FileInfo(outputFile); byte[] junkbytes = new byte[info.Length]; MemSet(junkbytes, 255); File.WriteAllBytes(outputFile, junkbytes); File.Delete(outputFile); } } this.Text = previousCaption; btnFirstPrototype.Enabled = true; this.UseWaitCursor = false; }
public static void Test() { using (PdfDocument document = new PdfDocument()) { PdfPage page = document.AddPage(); page.Width = XUnit.FromMillimeter(80).Point; page.Height = XUnit.FromMillimeter(800).Point; using (XGraphics gfx = XGraphics.FromPdfPage(page)) { XFont fontTicket = new XFont("Courier New", 9, XFontStyle.Regular); int baseX = 5; int baseY = 10; gfx.DrawString("************************************", fontTicket, XBrushes.Black, XUnit.FromMillimeter(baseX), XUnit.FromMillimeter(baseY += 5)); gfx.DrawString("*** Ticket ***", fontTicket, XBrushes.Black, XUnit.FromMillimeter(baseX), XUnit.FromMillimeter(baseY += 5)); gfx.DrawString("************************************", fontTicket, XBrushes.Black, XUnit.FromMillimeter(baseX), XUnit.FromMillimeter(baseY += 5)); // Crop the PDF dimensions at the current height double height = XUnit.FromMillimeter(baseY + 10).Point; page.CropBox = new PdfRectangle(new XPoint(0, page.Height - height), new XSize(page.Width, height)); document.Save("ticket.pdf"); } // End Using gfx } // End Using document } // End Sub