///<summary>Converts pixels used by us (100dpi) to points used by PdfSharp.</summary> public static float PixelsToPoints(float pixels) { double inches = pixels / 100d; //100 ppi XUnit xunit = XUnit.FromInch(inches); return((float)xunit.Point); }
/*//<summary>Converts pixels used by us to points used by PdfSharp.</summary> * private double P(double pixels){ * return (double)pixels/100; * }*/ ///<summary>Converts pixels used by us to points used by PdfSharp.</summary> private static double p(int pixels) { XUnit xunit = XUnit.FromInch((double)pixels / 100d); //100 ppi return(xunit.Point); //XUnit.FromInch((double)pixels/100); }
///<summary>Converts points used by PdfSharp to pixels used by us (100dpi).</summary> public static float PointsToPixels(float points) { double pointsPerInch = XUnit.FromInch(1).Point; double inches = points / pointsPerInch; return((float)(inches * 100d)); //100dpi }
private static PdfPage CreatePage(PdfDocument pdfDocument) { var page = pdfDocument.AddPage(); page.Width = XUnit.FromInch(6); page.Height = XUnit.FromInch(9); return(page); }
private void DrawHeaders(XUnit yCoord, XUnit margin, XGraphics gfx) { XUnit xCoord = margin; XFont headerFont = new XFont("Verdana", 16, XFontStyle.Bold); gfx.DrawString("Name", headerFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); xCoord += XUnit.FromInch(2.5); gfx.DrawString("Quantity", headerFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); xCoord += XUnit.FromInch(1.5); gfx.DrawString("Income", headerFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); xCoord += XUnit.FromInch(1.5); gfx.DrawString("Profit", headerFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); }
PdfDocument CreateDocumentForPreview(PdfSettingDto settings, PdfDocumentOpenMode mode) { //todo implement sending template return(new PdfDocument()); string directory = ""; PdfDocument document; if (string.IsNullOrEmpty(settings.Template)) { // check if user didn't setup manual page size, will setup it like A4 format if (settings.PageHeight == null) { settings.PageHeight = 11.7; } if (settings.PageWidth == null) { settings.PageWidth = 8.3; } document = new PdfDocument(); var initPage = document.AddPage(); initPage.Height = XUnit.FromInch(settings.PageHeight.Value); initPage.Width = XUnit.FromInch(settings.PageWidth.Value); //document should be imported so I have to reopen it using (MemoryStream ms = new MemoryStream()) { document.Save(ms, false); document = PdfReader.Open(ms, mode); } } else { if (settings.Template.IsBase64()) { var pdfArr = Convert.FromBase64String(settings.Template); MemoryStream pdfStream = new MemoryStream(pdfArr, 0, pdfArr.Length); document = PdfReader.Open(pdfStream, mode); } else { //var serverUtil = WorkingContext.HttpContext.Server; //directory = serverUtil.MapPath($"/PDFs/{ExecutingUser.Schema}/Templates"); //if (!Directory.Exists(directory)) throw new DirectoryNotFoundException($"{directory} not found"); //string path = Path.Combine(directory, settings.Template); //document = PdfReader.Open(path, mode); } } return(document); }
page.Height = new XUnit() { Centimeter = 21.75 }; page.Width = new XUnit() { Centimeter = 13.9 }; XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawImage(XImage.FromStream(imageStream), new XPoint(XUnit.FromInch(point.Item1), XUnit.FromInch(point.Item2))); const string filename = "PageSizes_tempfile.pdf"; document.Save(filename); }
public static void PDFExport(string Paydate) { string InvoiceNumber = "" + SelectedInvoiceNumber + ""; PdfDocument document = new PdfDocument(); document.Info.Title = "Invoice"; document.Info.Author = "Jack Huckins"; document.Info.Subject = "Service Invoice"; PdfPage page = new PdfPage(); page = document.AddPage(); page.Width = XUnit.FromInch(8.5); page.Height = XUnit.FromInch(11); XGraphics gfx = default(XGraphics); gfx = XGraphics.FromPdfPage(page); XForm form = new XForm(document, XUnit.FromMillimeter(300), XUnit.FromMillimeter(300)); XGraphics formGfx = default(XGraphics); formGfx = XGraphics.FromForm(form); XGraphicsState state = default(XGraphicsState); state = formGfx.Save(); //..... Invoice Results GetInvResults(Paydate); PrepareInvoiceTop(formGfx, state, InvoiceNumber); PrepareInvoiceData(6, 217, formGfx); PrepareFooter(formGfx); state = formGfx.Save(); formGfx.Dispose(); gfx.DrawImage(form, 0, 0); //document.Save("c:\\Invoices\\Inv " + InvoiceNumber + ".pdf") SetReportPath(); document.Save(ReportPath); TimeConnector.Data.ActionLog.Insert("PDF Export", "" + InvoiceNumber + ""); //UpdatePDFLabel("30 second Check", Form1.lblPDFStatus); //var _with1 = ViewPDF; //_with1.PdfName = Export.ReportPath; //_with1.Show(); }
private void ExportThread(object zParam) { var zDocument = new PdfDocument(); zDocument.Options.ColorMode = PdfColorMode.Undefined; //zDocument.Options.NoCompression = true; var listFiles = (List <string>)zParam; Func <string> funcGetOutputPath = () => txtOutputPath.Text; var sOutputPth = txtOutputPath.InvokeFunc(funcGetOutputPath); listFiles.ForEach(sFile => { var zImgSrc = Image.FromFile(sFile); // wipe out any transparency on the images var zImgDestination = new Bitmap(zImgSrc.Width, zImgSrc.Height, PixelFormat.Format24bppRgb); zImgDestination.SetResolution(zImgSrc.HorizontalResolution, zImgSrc.VerticalResolution); var zImageGfx = Graphics.FromImage(zImgDestination); zImageGfx.Clear(Color.White); zImageGfx.DrawImage(zImgSrc, 0, 0); var zPage = zDocument.AddPage(new PdfPage() { Width = XUnit.FromInch((double)zImgSrc.Width / (double)zImgSrc.HorizontalResolution), Height = XUnit.FromInch((double)zImgSrc.Height / (double)zImgSrc.VerticalResolution) }); var zGfx = XGraphics.FromPdfPage(zPage); using (var zMem = new MemoryStream()) { zImgDestination.Save(zMem, ImageFormat.Bmp); // just for testing //zImgDestination.Save("C:\\temp.bmp", ImageFormat.Bmp); var zXImage = XImage.FromStream(zMem); zGfx.DrawImage(zXImage, new XPoint()); zXImage.Dispose(); } zImgDestination.Dispose(); zImgSrc.Dispose(); progressBar.InvokeAction(() => progressBar.Value++); }); zDocument.Save(sOutputPth); ConfigureControlState(false); m_zExportThread = null; }
/// <summary> /// Updates the page size settings based on the cross application settings (and measurement type) /// </summary> private void UpdatePageSize() { switch (CardMakerSettings.PrintPageMeasurementUnit) { case MeasurementUnit.Inch: m_zCurrentPage.Width = XUnit.FromInch((double)CardMakerSettings.PrintPageWidth); m_zCurrentPage.Height = XUnit.FromInch((double)CardMakerSettings.PrintPageHeight); break; case MeasurementUnit.Millimeter: m_zCurrentPage.Width = XUnit.FromMillimeter((double)CardMakerSettings.PrintPageWidth); m_zCurrentPage.Height = XUnit.FromMillimeter((double)CardMakerSettings.PrintPageHeight); break; case MeasurementUnit.Centimeter: m_zCurrentPage.Width = XUnit.FromCentimeter((double)CardMakerSettings.PrintPageWidth); m_zCurrentPage.Height = XUnit.FromCentimeter((double)CardMakerSettings.PrintPageHeight); break; } }
public void create(Image img, string title, Double widthInches, Double heightInches) { PdfDocument document = new PdfDocument(); document.Info.Title = title; PdfPage page = document.AddPage(); page.Orientation = PageOrientation.Landscape; page.Height = XUnit.FromInch(heightInches); page.Width = XUnit.FromInch(widthInches); using (XGraphics gfx = XGraphics.FromPdfPage(page)) { gfx.DrawImage(img, new Point(0, 0)); } const string filename = "HelloWorld2.pdf"; document.Save(filename); Process.Start(filename); }
private void AddTitle(IItemsSoldReportData sales, XUnit margin, PdfPage page, XGraphics gfx) { XUnit yCoord = margin; XFont font = new XFont("Verdana", 20, XFontStyle.Bold); var titleWord = sales.IsDailyReport() ? "Daily" : "Weekly"; gfx.DrawString(titleWord + " Inventory Sold Report", font, XBrushes.Black, new XRect(0, yCoord, page.Width, page.Height), XStringFormats.TopCenter); if (sales.IsDailyReport()) { gfx.DrawString(sales.GetDate().ToString("d MMMM, yyyy"), font, XBrushes.Black, new XRect(0, yCoord + XUnit.FromInch(0.4), page.Width, page.Height), XStringFormats.TopCenter); } else { XFont smallerTitleFont = new XFont("Verdana", 16, XFontStyle.Bold); gfx.DrawString(sales.GetDate().ToString("d MMMM, yyyy") + " - " + sales.GetDate().AddDays(6).ToString("d MMMM, yyyy"), smallerTitleFont, XBrushes.Black, new XRect(0, yCoord + XUnit.FromInch(0.4), page.Width, page.Height), XStringFormats.TopCenter); } }
static void Main(string[] args) { if (args.Length < 2) { System.Console.Out.WriteLine("usage: polyglot_pdfsharp filename outfile"); return; } string filename = args[0]; string outfile = args[1]; PdfDocument doc = new PdfDocument(); LayoutHelper layoutHelper = new LayoutHelper(doc, XUnit.FromInch(1.0), XUnit.FromInch(10.0), XUnit.FromInch(1.0), XUnit.FromInch(7.5)); XFont font = new XFont("Verdana", 12); XUnit indentLeft = XUnit.FromInch(.5); XmlDocument xml = new XmlDocument(); xml.Load(filename); foreach (XmlNode bookNode in xml.SelectNodes(@"//BIBLEBOOK")) { string bookName = bookNode.Attributes["bname"].Value; layoutHelper.PrintCentered(bookName, font); foreach (XmlNode chapterNode in bookNode.SelectNodes("CHAPTER")) { int chapterNumber = int.Parse(chapterNode.Attributes["cnumber"].Value); layoutHelper.PrintChapter(chapterNumber, font); foreach (XmlNode verseNode in chapterNode.SelectNodes("VERS")) { int verseNumber = int.Parse(verseNode.Attributes["vnumber"].Value); string verseText = verseNode.InnerText; layoutHelper.PrintVerse(verseNumber, indentLeft, font, verseText); } } } // Save the document... doc.Save(outfile); }
public bool generatePdf() { if (!File.Exists(scaleNamesPath)) { MessageBox.Show(scaleNamesPath + " is not a valid scale names file"); return(false); } string[] scaleNames = File.ReadAllLines(scaleNamesPath); PdfDocument pdf = new PdfDocument(); pdf.Info.Title = "My First PDF"; XFont font = new XFont("Microsoft Sans Serif", 12, XFontStyle.Regular); // Set all the page sizes and orientation PdfPage basicPage = pdf.AddPage(); basicPage.Orientation = PageOrientation.Landscape; basicPage.Width = XUnit.FromInch(11); basicPage.Height = XUnit.FromInch(8.5); XGraphics graphBasic = XGraphics.FromPdfPage(basicPage); PdfPage page2 = pdf.AddPage(); page2.Orientation = PageOrientation.Landscape; page2.Width = XUnit.FromInch(11); page2.Height = XUnit.FromInch(8.5); XGraphics graph2 = XGraphics.FromPdfPage(page2); PdfPage page3 = pdf.AddPage(); page3.Orientation = PageOrientation.Landscape; page3.Width = XUnit.FromInch(11); page3.Height = XUnit.FromInch(8.5); XGraphics graph3 = XGraphics.FromPdfPage(page3); PdfPage page4 = pdf.AddPage(); page4.Orientation = PageOrientation.Landscape; page4.Width = XUnit.FromInch(11); page4.Height = XUnit.FromInch(8.5); XGraphics graph4 = XGraphics.FromPdfPage(page4); PdfPage page5 = pdf.AddPage(); page5.Orientation = PageOrientation.Landscape; page5.Width = XUnit.FromInch(11); page5.Height = XUnit.FromInch(8.5); XGraphics gfx = XGraphics.FromPdfPage(page5); XGraphicsState gs = gfx.Save(); gfx.TranslateTransform(600, 750); gfx.RotateTransform(-90); gfx.TranslateTransform(-600, -750); XTextFormatter tf = new XTextFormatter(gfx); tf.DrawString(critOutputPrimary, font, XBrushes.Black, new XRect(800, 200, 500, 500), XStringFormats.TopLeft); gfx.Restore(gs); // If the person has too many entries on the crit items page // It overflows here to another page if (critOutputSecondary != "") { PdfPage page6 = pdf.AddPage(); page6.Orientation = PageOrientation.Landscape; page6.Width = XUnit.FromInch(11); page6.Height = XUnit.FromInch(8.5); XGraphics gfx2 = XGraphics.FromPdfPage(page6); XGraphicsState gs2 = gfx2.Save(); gfx2.TranslateTransform(600, 750); //gfx.ScaleTransform(0.6); gfx2.RotateTransform(-90); gfx2.TranslateTransform(-600, -750); XTextFormatter tf2 = new XTextFormatter(gfx2); tf2.DrawString(critOutputSecondary, font, XBrushes.Black, new XRect(800, 200, 500, 500), XStringFormats.TopLeft); //gfx.RotateTransform(-90); gfx2.Restore(gs2); } string[] userInfo = { "Name: " + testTaker.lastName + ", " + testTaker.firstName, "Gender: " + gender + " Address:______________________________", "Occupation:____________________ Date Tested: " + testTaker.date, "Education:_______ Age: " + testTaker.age + " Marital Status:________________", "Referred By:_________________________________________", "MMPI Code:_________________________________________" }; for (int i = 0; i < 6; i++) { graphBasic.DrawString(userInfo[i], font, XBrushes.Black, new XRect(430, (i * 15) + 15, 0, 0), XStringFormats.TopLeft); } // Logo in upper left graphBasic.DrawImage(XImage.FromFile(baseFolder + "logo.jpg"), new XRect(40, 15, 250, 110)); // Draw the charts onto the pdf try { graphBasic.DrawImage(XImage.FromFile(indivBasePath + "\\" + testTaker.lastName + testTaker.firstName + "1.png"), new XRect(30, 120, 760, 450)); graph2.DrawImage(XImage.FromFile(indivBasePath + "\\" + testTaker.lastName + testTaker.firstName + "2.png"), new XRect(-25, 0, 830, 615)); graph3.DrawImage(XImage.FromFile(indivBasePath + "\\" + testTaker.lastName + testTaker.firstName + "3.png"), new XRect(-25, 0, 830, 615)); graph4.DrawImage(XImage.FromFile(indivBasePath + "\\" + testTaker.lastName + testTaker.firstName + "4.png"), new XRect(-25, 0, 830, 615)); } catch (Exception) { MessageBox.Show("PDF Failed: Image in use - Try restarting the program"); return(false); } if (barLabel.Checked) { graph2.RotateAtTransform(-90, new XPoint(430, 430)); graph3.RotateAtTransform(-90, new XPoint(430, 430)); graph4.RotateAtTransform(-90, new XPoint(430, 430)); for (int i = 0; i < 26; i++) { graph2.DrawString(scaleNames[i], font, XBrushes.White, new XRect(330, (i * 28.66) + 41, 0, 0), XStringFormats.TopLeft); graph3.DrawString(scaleNames[i + 26], font, XBrushes.White, new XRect(328, (i * 28.66) + 41, 0, 0), XStringFormats.TopLeft); } for (int i = 0; i < 22; i++) { graph4.DrawString(scaleNames[i + 52], font, XBrushes.White, new XRect(328, (i * 33.96) + 43, 0, 0), XStringFormats.TopLeft); } } string pdfFilename = indivBasePath + testTaker.lastName + testTaker.firstName + ".pdf"; pdf.Save(pdfFilename); if (File.Exists(pdfFilename)) { MessageBox.Show("PDF Success at " + pdfFilename); } else { MessageBox.Show("PDF Failed at " + pdfFilename); return(false); } return(true); }
public void write(int paperFormatIndex, String fileName) { PageSize pageSize; paperFormatIndex++; switch (paperFormatIndex) { case (int)PageSize.A0: pageSize = PageSize.A0; break; case (int)PageSize.A1: pageSize = PageSize.A1; break; case (int)PageSize.A2: pageSize = PageSize.A2; break; case (int)PageSize.A3: pageSize = PageSize.A3; break; default: pageSize = PageSize.A4; break; } //Grayscale Map //Image grayscaledMap = MapWithQRCodeWriter.MakeGrayscale(map); // scale map Image scaledMap = this.scaleImageToFitFormat(pageSize, map); this.drawFrame(ref scaledMap); // get location int locationX = Convert.ToInt32(((this.codeSize / 2.0f) / scaledMap.Width) * map.Width); int locationY = Convert.ToInt32(((this.codeSize / 2.0f) / scaledMap.Height) * map.Height); PointLatLng location = MapOverlayForm.Instance.FromLocalToLatLng(locationX, locationY); // get scale int p1X = Convert.ToInt32((92.0f / scaledMap.Width) * map.Width); int p1Y = Convert.ToInt32((92.0f / scaledMap.Width) * map.Width); PointLatLng p1Location = MapOverlayForm.Instance.FromLocalToLatLng(p1X, p1Y); int p2X = Convert.ToInt32((356.0f / scaledMap.Width) * map.Width); int p2Y = Convert.ToInt32((92.0f / scaledMap.Width) * map.Width); PointLatLng p2Location = MapOverlayForm.Instance.FromLocalToLatLng(p2X, p2Y); double scale = MapOverlayForm.Instance.gMapControl.MapProvider.Projection.GetDistance(p1Location, p2Location); // create qr code com.google.zxing.qrcode.QRCodeWriter qrCode = new com.google.zxing.qrcode.QRCodeWriter(); String locationString = location.Lat.ToString() + ";" + location.Lng.ToString() + ";" + scale.ToString().Substring(0, 6); ByteMatrix byteIMG = qrCode.encode(locationString, com.google.zxing.BarcodeFormat.QR_CODE, this.codeSize, this.codeSize); // draw qr code on map image this.drawQRCodeOnImage(byteIMG, ref scaledMap); PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); page.Size = pageSize; page.Orientation = PageOrientation.Landscape; XGraphics gfx = XGraphics.FromPdfPage(page); XImage image = XImage.FromGdiPlusImage(scaledMap); XUnit imgHeight = XUnit.FromInch(image.PixelHeight / image.VerticalResolution); XUnit imgWidth = XUnit.FromInch(image.PixelWidth / image.HorizontalResolution); double width = image.PixelWidth * 72 / image.HorizontalResolution; double height = image.PixelHeight * 72 / image.VerticalResolution; gfx.DrawImage(image, (page.Width.Point - imgWidth.Point) / 2.0, (page.Height.Point - imgHeight.Point) / 2.0, width, height); try { document.Save(fileName); } catch (IOException) { System.Windows.Forms.MessageBox.Show("Could not save the file. Maybe the file is used by another program. ", "IO Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } document.Dispose(); }
private void btnPrint_Click_1(object sender, EventArgs e) { imageName(); if (themePath.Length <= 4) { MessageBox.Show("Please select theme path"); return; } if (!File.Exists(themePath)) { MessageBox.Show("Theme Path Does not exist"); return; } PdfDocument document = new PdfDocument(); document.Info.Title = "Created by Parth & Suhail"; PdfPage page; XGraphics gfx; page = document.AddPage(); page.Orientation = PdfSharp.PageOrientation.Portrait; page.Width = XUnit.FromInch(8.5); page.Height = XUnit.FromInch(11); gfx = XGraphics.FromPdfPage(page); int count = 0; foreach (DataRow dr in mainDt.Rows) { count++; if (count > 8) { count = 0; page = document.AddPage(); page.Orientation = PdfSharp.PageOrientation.Portrait; page.Width = XUnit.FromInch(8.5); page.Height = XUnit.FromInch(11); gfx = XGraphics.FromPdfPage(page); } ModelStudent obj = new ModelStudent(); obj.fullName = dr["Full Name"].ToString().ToUpper(); obj.nationalId = dr["Id"].ToString().ToUpper(); var mydate = Convert.ToDateTime(dr["DOB"].ToString()); if (isdateShort) { obj.DOB = mydate.ToShortDateString(); } else { obj.DOB = mydate.ToLongDateString(); } obj.studentImagePath = dr["path"].ToString(); Print.setCard(gfx, count, TextColor, imageFramePath, obj, themePath); } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Pdf|*.pdf"; saveFileDialog.Title = "Save Document As Pdf File"; DialogResult result = saveFileDialog.ShowDialog(); saveFileDialog.RestoreDirectory = true; if (result == DialogResult.OK && saveFileDialog.FileName != "") { try { if (saveFileDialog.CheckPathExists) { document.Save(saveFileDialog.FileName); Process.Start(saveFileDialog.FileName); MessageBox.Show("Document saved successfully"); } else { MessageBox.Show("Given Path does not exist"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
private void GeneratePDF() { try { double myX = 3 * 72; double myY = 7.5 * 72; double someWidth = 126; double someHeight = 36; string pdfloc = LlamaBrowser.Address.Substring(LlamaBrowser.Address.IndexOf(@"file:///")).Replace(@"file:///", ""); var tempdocument = PdfReader.Open(pdfloc); //PdfDocument tempdocument = new PdfDocument(PDFPath); PdfPages temppages = tempdocument.Pages; int pagecount = temppages.Count; PdfPage temppage = temppages[0]; if (pagecount == 1) { temppage = temppages[0]; } else if (pagecount > 1) { int pageindex = (pagecount - 1); temppage = temppages[pageindex]; } temppage.Orientation = PageOrientation.Portrait; temppage.Width = XUnit.FromInch(8.5); temppage.Height = XUnit.FromInch(11); XGraphics gfx = XGraphics.FromPdfPage(temppage, XPageDirection.Downwards); MemoryStream stream = new MemoryStream(); _SigTransparent.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Byte[] bytes = stream.ToArray(); gfx.DrawImage(XImage.FromStream(stream), myX, myY, someWidth, someHeight); //gfx.DrawImage(XImage.FromStream(_SigStream), 0, 0); SaveFileDialog LlamaSaves = new SaveFileDialog(); LlamaSaves.Filter = "PDF |*.pdf"; LlamaSaves.Title = "Save PDF"; LlamaSaves.ShowDialog(); if (LlamaSaves.FileName != "") { FileStream fs = (FileStream)LlamaSaves.OpenFile(); switch (LlamaSaves.FilterIndex) { case 1: tempdocument.Save(fs, true); break; } fs.Close(); } // _SigStream.Dispose(); tempdocument.Dispose(); gfx.Dispose(); stream.Dispose(); _SigTransparent.Dispose(); } catch (Exception Err) { System.Windows.MessageBox.Show(Err.Message); } }
/// <summary> /// Generates a barcode PDF and returns the number of barcodes generated /// </summary> /// <param name="outputPath"></param> /// <param name="numberOfPages"></param> /// <returns>The number of barcodes generated</returns> public int GenerateBarcodes(string outputPath) { if (NumberOfPages > 0) { PdfDocument document = new PdfDocument(); document.Info.Title = "Inventory Barcodes"; long barcodeToUse = GeneratedBarcode.GetLatestBarcodeNumber() + 1; var barcodesGenerated = new List <long>(); for (int i = 0; i < NumberOfPages; i++) { PdfPage page = document.AddPage(); page.Size = PageSize; XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.Bold); XUnit yCoord = XUnit.FromInch(1); // pixels gfx.DrawString("Inventory Barcodes", font, XBrushes.Black, new XRect(0, yCoord, page.Width, page.Height), XStringFormats.TopCenter); yCoord += XUnit.FromInch(0.7); // Generate a barcode var barcodeCreator = new BarcodeLib.Barcode(); barcodeCreator.ImageFormat = ImageFormat.Jpeg; barcodeCreator.IncludeLabel = true; barcodeCreator.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER; barcodeCreator.Alignment = BarcodeLib.AlignmentPositions.CENTER; bool isPageFull = false; XUnit imageHeight = XUnit.FromPoint(60); while (!isPageFull) { var isWidthFull = false; XUnit xCoord = XUnit.FromInch(1); while (!isWidthFull) { var image = barcodeCreator.Encode(BarcodeType, barcodeToUse.ToString()); if (image != null) { // make sure images are a good size based on DPI // TODO: There has got to be a better way to make things fairly consistent across computers // with different DPI. This is ridiculous. I love WPF most of the time with its DPI // help, but in this case.......ugh. Images come out a little blurry this way // on computers with a non-192 DPI. double ratioTo192 = (192 / image.VerticalResolution); int resizeHeight = (int)(image.Height / ratioTo192); int resizeWidth = (int)(image.Width / ratioTo192); image = ResizeImage(image, resizeWidth, resizeHeight, (int)image.VerticalResolution); // ok, now we can draw. XImage pdfImage = XImage.FromBitmapSource(ConvertImageToBitmapImage(image)); gfx.DrawImage(pdfImage, xCoord, yCoord); xCoord += XUnit.FromPoint(pdfImage.PointWidth); imageHeight = XUnit.FromPoint(pdfImage.PointHeight); var blah = XUnit.FromPoint(image.Width); XUnit spaceBetweenBarcodes = XUnit.FromInch(0.75); if (xCoord + XUnit.FromPoint(pdfImage.PointWidth) + spaceBetweenBarcodes > page.Width - XUnit.FromInch(1)) { isWidthFull = true; } barcodesGenerated.Add(barcodeToUse); barcodeToUse++; xCoord += spaceBetweenBarcodes; } else { // failure case isWidthFull = true; isPageFull = true; break; } } yCoord += imageHeight; yCoord += XUnit.FromInch(0.7); if (yCoord + imageHeight > page.Height - XUnit.FromInch(1)) { isPageFull = true; } } } if (!IsDryRun) { // save the fact that we generated barcodes GeneratedBarcode.AddGeneratedCodes(barcodesGenerated, DateTime.Now, 1); // save the document and start the process for viewing the pdf document.Save(outputPath); Process.Start(outputPath); } return(barcodesGenerated.Count); } return(0); }
private void buttonScanPages_Click(object sender, RoutedEventArgs e) { // select device if this failed at startup if (string.IsNullOrEmpty(_deviceId)) { if (!SelectDevice()) { return; } } try { Mouse.OverrideCursor = Cursors.Wait; _width = Convert.ToDouble(textBoxWidth.Text, CultureInfo.CurrentCulture); _height = Convert.ToDouble(textBoxHeight.Text, CultureInfo.CurrentCulture); _adf = (checkBoxADF.IsChecked == true); XImage ximage = null; while ((ximage = ScanOne()) != null) { PdfPage page = _doc.AddPage(); page.Width = XUnit.FromInch(_width); page.Height = XUnit.FromInch(_height); using (XGraphics g = XGraphics.FromPdfPage(page)) { g.DrawImage(ximage, 0, 0); ximage.Dispose(); } // flag that the document needs saving _docSaved = false; // only scan one page if not using the ADF if (!_adf) { break; } UpdateState(); } } catch (Exception ex) { Mouse.OverrideCursor = null; UserSettings.Settings.LogException(LogSeverity.Warning, "Failed to scan page", ex); CatfoodMessageBox.Show(MainWindow.MessageBoxIcon, this, string.Format(CultureInfo.InvariantCulture, "{0} ({1})", WiaErrorOrMessage(ex), _lastItem), "Failed to scan - Catfood PdfScan", CatfoodMessageBoxType.Ok, CatfoodMessageBoxIcon.Error, ex); } finally { Mouse.OverrideCursor = null; UpdateState(); } }
private void CalculateImageDimensions() { ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; if (formatInfo.failure == ImageFailure.None) { XImage xImage = null; try { xImage = XImage.FromFile(this.imageFilePath); } catch (InvalidOperationException ex) { Trace.WriteLine(Messages.InvalidImageType(ex.Message)); formatInfo.failure = ImageFailure.InvalidType; } try { XUnit usrWidth = image.Width.Point; XUnit usrHeight = image.Height.Point; bool usrWidthSet = !this.image.IsNull("Width"); bool usrHeightSet = !this.image.IsNull("Height"); XUnit resultWidth = usrWidth; XUnit resultHeight = usrHeight; double xPixels = xImage.PixelWidth; bool usrResolutionSet = !image.IsNull("Resolution"); double horzRes = usrResolutionSet ? (double)image.Resolution : xImage.HorizontalResolution; XUnit inherentWidth = XUnit.FromInch(xPixels / horzRes); double yPixels = xImage.PixelHeight; double vertRes = usrResolutionSet ? (double)image.Resolution : xImage.VerticalResolution; XUnit inherentHeight = XUnit.FromInch(yPixels / vertRes); bool lockRatio = this.image.IsNull("LockAspectRatio") ? true : image.LockAspectRatio; double scaleHeight = this.image.ScaleHeight; double scaleWidth = this.image.ScaleWidth; bool scaleHeightSet = !this.image.IsNull("ScaleHeight"); bool scaleWidthSet = !this.image.IsNull("ScaleWidth"); if (lockRatio && !(scaleHeightSet && scaleWidthSet)) { if (usrWidthSet && !usrHeightSet) { resultHeight = inherentHeight / inherentWidth * usrWidth; } else if (usrHeightSet && !usrWidthSet) { resultWidth = inherentWidth / inherentHeight * usrHeight; } else if (!usrHeightSet && !usrWidthSet) { resultHeight = inherentHeight; resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; resultWidth = resultWidth * scaleHeight; } if (scaleWidthSet) { resultHeight = resultHeight * scaleWidth; resultWidth = resultWidth * scaleWidth; } } else { if (!usrHeightSet) { resultHeight = inherentHeight; } if (!usrWidthSet) { resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; } if (scaleWidthSet) { resultWidth = resultWidth * scaleWidth; } } formatInfo.CropWidth = (int)xPixels; formatInfo.CropHeight = (int)yPixels; if (!this.image.IsNull("PictureFormat")) { PictureFormat picFormat = this.image.PictureFormat; //Cropping in pixels. XUnit cropLeft = picFormat.CropLeft.Point; XUnit cropRight = picFormat.CropRight.Point; XUnit cropTop = picFormat.CropTop.Point; XUnit cropBottom = picFormat.CropBottom.Point; formatInfo.CropX = (int)(horzRes * cropLeft.Inch); formatInfo.CropY = (int)(vertRes * cropTop.Inch); formatInfo.CropWidth -= (int)(horzRes * ((XUnit)(cropLeft + cropRight)).Inch); formatInfo.CropHeight -= (int)(vertRes * ((XUnit)(cropTop + cropBottom)).Inch); //Scaled cropping of the height and width. double xScale = resultWidth / inherentWidth; double yScale = resultHeight / inherentHeight; cropLeft = xScale * cropLeft; cropRight = xScale * cropRight; cropTop = yScale * cropTop; cropBottom = yScale * cropBottom; resultHeight = resultHeight - cropTop - cropBottom; resultWidth = resultWidth - cropLeft - cropRight; } if (resultHeight <= 0 || resultWidth <= 0) { formatInfo.Width = XUnit.FromCentimeter(2.5); formatInfo.Height = XUnit.FromCentimeter(2.5); Trace.WriteLine(Messages.EmptyImageSize); this.failure = ImageFailure.EmptySize; } else { formatInfo.Width = resultWidth; formatInfo.Height = resultHeight; } } catch (Exception ex) { Trace.WriteLine(Messages.ImageNotReadable(this.image.Name, ex.Message)); formatInfo.failure = ImageFailure.NotRead; } finally { if (xImage != null) { xImage.Dispose(); } } } if (formatInfo.failure != ImageFailure.None) { if (!this.image.IsNull("Width")) { formatInfo.Width = this.image.Width.Point; } else { formatInfo.Width = XUnit.FromCentimeter(2.5); } if (!this.image.IsNull("Height")) { formatInfo.Height = this.image.Height.Point; } else { formatInfo.Height = XUnit.FromCentimeter(2.5); } return; } }
public string GerarPDF(EmitiCertificado certificado) { var codigo = Db.ParticipanteEvento.FirstOrDefault (x => x.ParticipanteId == certificado.UsuarioId && x.EventoId == certificado.EventoId && x.ConfirmacaoPresenca == true); var usuario = Db.Usuario.Find(certificado.UsuarioId); var participante = Db.Participante.Find(usuario.Id); var evento = Db.Evento.Find(certificado.EventoId); var agenda = Db.AgendaEvento.Find(evento.AgendaEventoId); if (usuario == null) { return("Usuario não encontrado."); } if (evento == null) { return("Evento não encontrado."); } if (agenda == null) { return("Agenda não encontrada."); } //gera certificado var doc = new PdfDocument(); var page = doc.AddPage(); page.Height = XUnit.FromInch(5.5); var graphics = XGraphics.FromPdfPage(page); var textFormatter = new PdfSharp.Drawing.Layout.XTextFormatter(graphics); var fontCertificado = new XFont("Arial", 30, XFontStyle.Bold); graphics.DrawImage(XImage.FromFile(@"C:\Users\Markim\Documents\KonohaAPI\KonohaApi\bg.png") , 0, 0, page.Width + 60, page.Height); textFormatter.DrawString("Certificado Konoha ", fontCertificado, XBrushes.Black, new XRect(160, 110, page.Width, page.Height)); textFormatter.Alignment = PdfSharp.Drawing.Layout.XParagraphAlignment.Justify; textFormatter.DrawString($"Certificamos para os devidos fins que {usuario.Nome}, CPF n.º {usuario.Cpf} participou do (a) {evento.TipoEvento} " + $"'{evento.Nome}' ministrado(a) pelo(a) {evento.Apresentador}, durante a {agenda.Nome}, no período de {agenda.DataInicio.Day} a " + $"{agenda.DateEncerramento.Day} de {agenda.DataInicio.ToString("MMMM")} de {agenda.DataInicio.Year} com carga horária de {evento.CargaHoraria} horas." , new XFont("Arial", 14, XFontStyle.Regular) , XBrushes.Black, new XRect(30, 180, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Código de validação:", new XFont("Arial", 10, XFontStyle.Bold), XBrushes.Black, new XRect(397, 370, page.Width - 60, page.Height - 60)); textFormatter.DrawString(codigo.CodigoValidacao, new XFont("Arial", 10, XFontStyle.Regular), XBrushes.Black, new XRect(500, 370, page.Width - 60, page.Height - 60)); string caminho = @"C:\Users\Markim\Documents\KonohaAPI\KonohaApi\Certificados\Certificado" + codigo.CodigoValidacao + ".pdf"; doc.Save(caminho); return(caminho); }
public PaperTarget(string name, System.Drawing.Printing.PaperSize pageSize) { Name = name; _width = XUnit.FromInch(((double)pageSize.Width) / 100d); _height = XUnit.FromInch(((double)pageSize.Height) / 100d); }
/// <summary> /// Method to query for pdf version of labels /// </summary> /// <param name="labels">list of labels deails</param> /// <param name="doc">pdf document to append more label</param> /// <returns>reutnr</returns> public PdfDocument PrintLabels(List <Labeldetails> labels, PdfDocument doc) { var client = new RestClient(); client.BaseUrl = new Uri("http://nz.api.fastway.org/v2/"); var request = new RestRequest(); //For printng labels request.Resource = "dynamiclabels/generatelabel"; this.RequestPopulating(request, labels[0]); if (labels[0].toAddress2 != "") { request.AddParameter("toAddress2", labels[0].toAddress2); } for (int i = 0; i < labels.Count; i++) { request.AddParameter(string.Concat("items[", i, "].colour"), labels[i].labelColour); request.AddParameter(string.Concat("items[", i, "].labelNumber"), labels[i].labelNumber); request.AddParameter(string.Concat("items[", i, "].weight"), labels[i].weight + " kg"); request.AddParameter(string.Concat("items[", i, "].numberOfExcess"), labels[i].excess); if (labels[i].reference != "") { request.AddParameter("customerReference", labels[i].reference); } } //Execute API request, await for response IRestResponse response = client.Execute(request); //Parsing reresponse JObject o = JObject.Parse(response.Content); //Parsing result portion of response to get jpeg image strings try { JArray a = JArray.Parse(o["result"]["jpegs"].ToString()); for (int j = 0; j < a.Count; j++) { byte[] jpgByteArray = Convert.FromBase64String(a[j]["base64Utf8Bytes"].ToString()); PdfPage page = doc.AddPage(); page.Width = XUnit.FromInch(4); page.Height = XUnit.FromInch(6); MemoryStream stream = new MemoryStream(jpgByteArray); XImage image = XImage.FromStream(stream); XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawImage(image, 0, 0, 285, 435); } if (labels[0].ruralNumber != null && labels[0].ruralNumber != "") { var clientRural = new RestClient(); clientRural.BaseUrl = new Uri("http://nz.api.fastway.org/v2/"); var requestRural = new RestRequest(); requestRural.Resource = "dynamiclabels/generatelabel"; this.RequestPopulating(requestRural, labels[0]); if (labels[0].toAddress2 != "") { requestRural.AddParameter("toAddress2", labels[0].toAddress2); } for (int l = 0; l < labels.Count; l++) { requestRural.AddParameter(string.Concat("items[", l, "].colour"), "RURAL"); requestRural.AddParameter(string.Concat("items[", l, "].labelNumber"), labels[l].ruralNumber); requestRural.AddParameter(string.Concat("items[", l, "].weight"), labels[l].weight + " kg"); if (labels[l].reference != "") { requestRural.AddParameter("customerReference", labels[l].reference); } } IRestResponse responseRural = clientRural.Execute(requestRural); //Parsing response JObject oRural = JObject.Parse(responseRural.Content); JArray aRural = JArray.Parse(oRural["result"]["jpegs"].ToString()); for (int k = 0; k < aRural.Count; k++) { byte[] jpgRuralByteArray = Convert.FromBase64String(aRural[k]["base64Utf8Bytes"].ToString()); PdfPage page = doc.AddPage(); page.Width = XUnit.FromInch(4); page.Height = XUnit.FromInch(6); MemoryStream stream = new MemoryStream(jpgRuralByteArray); XImage image = XImage.FromStream(stream); XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawImage(image, 0, 0, 285, 435); } } if (labels[0].saturdayNumber != null && labels[0].saturdayNumber != "") { var clientSaturday = new RestClient(); clientSaturday.BaseUrl = new Uri("http://nz.api.fastway.org/v2/"); var requestSaturday = new RestRequest(); requestSaturday.Resource = "dynamiclabels/generatelabel"; this.RequestPopulating(requestSaturday, labels[0]); if (labels[0].toAddress2 != "") { requestSaturday.AddParameter("toAddress2", labels[0].toAddress2); } for (int l = 0; l < labels.Count; l++) { requestSaturday.AddParameter(string.Concat("items[", l, "].colour"), "SATURDAY"); requestSaturday.AddParameter(string.Concat("items[", l, "].labelNumber"), labels[l].saturdayNumber); requestSaturday.AddParameter(string.Concat("items[", l, "].weight"), labels[l].weight + " kg"); if (labels[l].reference != "") { requestSaturday.AddParameter("customerReference", labels[l].reference); } } IRestResponse responseSaturday = clientSaturday.Execute(requestSaturday); //Parsing response JObject oSaturday = JObject.Parse(responseSaturday.Content); JArray aSaturday = JArray.Parse(oSaturday["result"]["jpegs"].ToString()); for (int k = 0; k < aSaturday.Count; k++) { byte[] jpgRuralByteArray = Convert.FromBase64String(aSaturday[k]["base64Utf8Bytes"].ToString()); PdfPage page = doc.AddPage(); page.Width = XUnit.FromInch(4); page.Height = XUnit.FromInch(6); MemoryStream stream = new MemoryStream(jpgRuralByteArray); XImage image = XImage.FromStream(stream); XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawImage(image, 0, 0, 285, 435); } } return(doc); } catch (Exception e) { return(doc); throw e; } }
/// <summary> /// Method to query for pdfstreams on label numbers //NOTE: Currently not active /// </summary> /// <param name="labelNumbers">Fastway label numbers</param> /// <param name="apiKey">Fastway apiKey</param> /// <returns>string content from API call response</returns> public string PrintLabelNumbersPdf(List <string> labelNumbers, string apiKey) { //RestClient to make API calls var client = new RestClient(); client.BaseUrl = new Uri("http://nz.api.fastway.org/v2/"); //New restclient request var request = new RestRequest(); //populate data required for API calls request.Resource = "dynamiclabels/generate-label-for-labelnumber"; for (int i = 0; i < labelNumbers.Count; i++) {//add labels numbers request.AddParameter(string.Concat("LabelNumbers[", i, "]"), labelNumbers[i]); } //Fastway api key request.AddParameter("api_key", apiKey); // Get label using image type request.AddParameter("Type", "Image"); //Execute API request, await for response IRestResponse response = client.Execute(request); //Parsing reresponse JObject o = JObject.Parse(response.Content); //Parsing result portion of response to get jpeg image strings try { JArray a = JArray.Parse(o["result"]["jpegs"].ToString()); List <string> labels = new List <string>(); PdfDocument doc = new PdfDocument(); for (int j = 0; j < a.Count; j++) { byte[] jpgByteArray = Convert.FromBase64String(a[j]["base64Utf8Bytes"].ToString()); PdfPage page = doc.AddPage(); page.Width = XUnit.FromInch(4); page.Height = XUnit.FromInch(6); MemoryStream stream = new MemoryStream(jpgByteArray); XImage image = XImage.FromStream(stream); XGraphics gfx = XGraphics.FromPdfPage(page); gfx.DrawImage(image, 0, 0, 285, 435); } MemoryStream pdfStream = new MemoryStream(); doc.Save(pdfStream, false); byte[] pdfBytes = pdfStream.ToArray(); var pdfBase64Code = Convert.ToBase64String(pdfBytes); return(pdfBase64Code); } catch (Exception e) { throw e; } }
public async Task drawPdf() { // string text = null; List <Module> modules = new List <Module>(); Task t = Task.Run(() => { modules = getModuleData(); }); await Task.WhenAll(t); pdf.Info.Title = "The first PDF document"; pdfPage = pdf.AddPage(); XGraphics graph = XGraphics.FromPdfPage(pdfPage); font = new XFont("Verdana", 15, XFontStyle.Bold); font2 = new XFont("Verdana", 10); XStringFormat format = new XStringFormat(); tf = new XTextFormatter(graph); pdfPage.Orientation = PdfSharp.PageOrientation.Portrait; pdfPage.Width = XUnit.FromInch(8.5); pdfPage.Height = XUnit.FromInch(11); getTitlePage(); Dictionary <string, string> p = Module.getModuleData(data.Token, data.Lang, data.ModuleName); foreach (KeyValuePair <string, string> k in p) { double newHeight = someHeight; string value = ""; if (k.Value != null) { value = k.Value; double stringSpaceLength = value.Count(Char.IsWhiteSpace); newHeight += (stringSpaceLength / 12) * 11 + 50; newHeight += (Regex.Matches(value, @"\r\n").Count * 5); if (pdfPage.Height < myY + newHeight && entryNumber != 1) { myY = 50; pdfPage = pdf.AddPage(); graph = XGraphics.FromPdfPage(pdfPage); tf = new XTextFormatter(graph); } drawSomething(myY, pdfPage.Height, newHeight, k.Key, value); if (!heightIsUpdated) { myY += newHeight; } else { heightIsUpdated = false; } entryNumber++; } } string pdfFilename = data.ModuleName + ".pdf"; try { pdf.Save(pdfFilename); } catch { Console.WriteLine("already in use"); } Process.Start(pdfFilename); }
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 CalculateImageDimensions() { ImageFormatInfo formatInfo = (ImageFormatInfo)_renderInfo.FormatInfo; if (formatInfo.Failure == ImageFailure.None) { XImage xImage = null; try { //xImage = XImage.FromFile(_imageFilePath); xImage = CreateXImage(_imageFilePath); } catch (InvalidOperationException ex) { Debug.WriteLine(Messages2.InvalidImageType(ex.Message)); formatInfo.Failure = ImageFailure.InvalidType; } if (formatInfo.Failure == ImageFailure.None) { try { XUnit usrWidth = _image.Width.Point; XUnit usrHeight = _image.Height.Point; bool usrWidthSet = !_image._width.IsNull; bool usrHeightSet = !_image._height.IsNull; XUnit resultWidth = usrWidth; XUnit resultHeight = usrHeight; Debug.Assert(xImage != null); double xPixels = xImage.PixelWidth; bool usrResolutionSet = !_image._resolution.IsNull; double horzRes = usrResolutionSet ? _image.Resolution : xImage.HorizontalResolution; double vertRes = usrResolutionSet ? _image.Resolution : xImage.VerticalResolution; // ReSharper disable CompareOfFloatsByEqualityOperator if (horzRes == 0 && vertRes == 0) { horzRes = 72; vertRes = 72; } else if (horzRes == 0) { Debug.Assert(false, "How can this be?"); horzRes = 72; } else if (vertRes == 0) { Debug.Assert(false, "How can this be?"); vertRes = 72; } // ReSharper restore CompareOfFloatsByEqualityOperator XUnit inherentWidth = XUnit.FromInch(xPixels / horzRes); double yPixels = xImage.PixelHeight; XUnit inherentHeight = XUnit.FromInch(yPixels / vertRes); //bool lockRatio = _image.IsNull("LockAspectRatio") ? true : _image.LockAspectRatio; bool lockRatio = _image._lockAspectRatio.IsNull || _image.LockAspectRatio; double scaleHeight = _image.ScaleHeight; double scaleWidth = _image.ScaleWidth; //bool scaleHeightSet = !_image.IsNull("ScaleHeight"); //bool scaleWidthSet = !_image.IsNull("ScaleWidth"); bool scaleHeightSet = !_image._scaleHeight.IsNull; bool scaleWidthSet = !_image._scaleWidth.IsNull; if (lockRatio && !(scaleHeightSet && scaleWidthSet)) { if (usrWidthSet && !usrHeightSet) { resultHeight = inherentHeight / inherentWidth * usrWidth; } else if (usrHeightSet && !usrWidthSet) { resultWidth = inherentWidth / inherentHeight * usrHeight; } // ReSharper disable once ConditionIsAlwaysTrueOrFalse else if (!usrHeightSet && !usrWidthSet) { resultHeight = inherentHeight; resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; resultWidth = resultWidth * scaleHeight; } if (scaleWidthSet) { resultHeight = resultHeight * scaleWidth; resultWidth = resultWidth * scaleWidth; } } else { if (!usrHeightSet) { resultHeight = inherentHeight; } if (!usrWidthSet) { resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; } if (scaleWidthSet) { resultWidth = resultWidth * scaleWidth; } } formatInfo.CropWidth = (int)xPixels; formatInfo.CropHeight = (int)yPixels; if (_image._pictureFormat != null && !_image._pictureFormat.IsNull()) { PictureFormat picFormat = _image.PictureFormat; //Cropping in pixels. XUnit cropLeft = picFormat.CropLeft.Point; XUnit cropRight = picFormat.CropRight.Point; XUnit cropTop = picFormat.CropTop.Point; XUnit cropBottom = picFormat.CropBottom.Point; formatInfo.CropX = (int)(horzRes * cropLeft.Inch); formatInfo.CropY = (int)(vertRes * cropTop.Inch); formatInfo.CropWidth -= (int)(horzRes * ((XUnit)(cropLeft + cropRight)).Inch); formatInfo.CropHeight -= (int)(vertRes * ((XUnit)(cropTop + cropBottom)).Inch); //Scaled cropping of the height and width. double xScale = resultWidth / inherentWidth; double yScale = resultHeight / inherentHeight; cropLeft = xScale * cropLeft; cropRight = xScale * cropRight; cropTop = yScale * cropTop; cropBottom = yScale * cropBottom; resultHeight = resultHeight - cropTop - cropBottom; resultWidth = resultWidth - cropLeft - cropRight; } if (resultHeight <= 0 || resultWidth <= 0) { formatInfo.Width = XUnit.FromCentimeter(2.5); formatInfo.Height = XUnit.FromCentimeter(2.5); Debug.WriteLine(Messages2.EmptyImageSize); _failure = ImageFailure.EmptySize; } else { formatInfo.Width = resultWidth; formatInfo.Height = resultHeight; } } catch (Exception ex) { Debug.WriteLine(Messages2.ImageNotReadable(_image.Name, ex.Message)); formatInfo.Failure = ImageFailure.NotRead; } finally { if (xImage != null) { xImage.Dispose(); } } } } if (formatInfo.Failure != ImageFailure.None) { if (!_image._width.IsNull) { formatInfo.Width = _image.Width.Point; } else { formatInfo.Width = XUnit.FromCentimeter(2.5); } if (!_image._height.IsNull) { formatInfo.Height = _image.Height.Point; } else { formatInfo.Height = XUnit.FromCentimeter(2.5); } } }
public void create(FNSkuLabel label, string condition, int copies, Double widthInches, Double heightInches) { // Create a new PDF document PdfDocument document = new PdfDocument(); document.Info.Title = label.FNSKU; int ImageHeight = 0; for (int i = 0; i < copies; i++) { // Create an empty page PdfPage page = document.AddPage(); page.Orientation = PageOrientation.Landscape; page.Height = XUnit.FromInch(heightInches); page.Width = XUnit.FromInch(widthInches); // Get an XGraphics object for drawing using (XGraphics gfx = XGraphics.FromPdfPage(page)) { using (FNSKUBarcode bc = new FNSKUBarcode(label.FNSKU)) { var barCodeImage = bc.getBarCodeImage(1); ImageHeight = barCodeImage.Height; var xOffsetBcToCenter = (page.Width - barCodeImage.Width) / 2; if (xOffsetBcToCenter < 0) { xOffsetBcToCenter = 0; } gfx.DrawImage(barCodeImage, new Point((int)xOffsetBcToCenter + 20, 2)); } string labelToFit = label.Title; bool fit = false; int fontSize = 10; var font = new XFont("Verdana", fontSize); XSize sizeText = new XSize(); while (!fit) { // Create a font sizeText = gfx.MeasureString(labelToFit, font); if (sizeText.Width < page.Width) { fit = true; } else { if (fontSize > minFontSize) { fontSize--; font = new XFont("Verdana", fontSize); } else { string[] words = labelToFit.Split(' '); if (words.Length > 1) { if (words[words.Length / 2].Length <= 0) { labelToFit = labelToFit.Remove(labelToFit.Length / 2, 2); } else { labelToFit = labelToFit.Replace(words[words.Length / 2], ""); } } else { labelToFit = labelToFit.Remove(labelToFit.Length / 2, 1); } } } } Double xOffsetToCenter = (page.Width - sizeText.Width) / 2; gfx.DrawString(labelToFit, font, XBrushes.Black, new PointF((float)xOffsetToCenter, ImageHeight + 3)); sizeText = gfx.MeasureString(label.FNSKU, font); xOffsetToCenter = (page.Width - sizeText.Width) / 2; gfx.DrawString(label.FNSKU, font, XBrushes.Black, new PointF((float)xOffsetToCenter, (float)ImageHeight + (float)sizeText.Height + 6.0f)); sizeText = gfx.MeasureString(condition, font); xOffsetToCenter = (page.Width - sizeText.Width) / 2; gfx.DrawString(condition, font, XBrushes.Black, new PointF((float)xOffsetToCenter, (float)ImageHeight + (float)sizeText.Height * 2 + 8.0f)); // Draw the text //gfx.DrawString(label.title, font, XBrushes.Black, //new XRect(i.Height+1, 0, page.Width, page.Height), //XStringFormats.Center); // Save the document... } } const string filename = "HelloWorld.pdf"; document.Save(filename); Process.Start(filename); }
public void GeneratePDF(IItemsSoldReportData sales, string outputPath) { PdfDocument document = new PdfDocument(); var titleWord = sales.IsDailyReport() ? "Daily" : "Weekly"; document.Info.Title = titleWord + " Inventory Sold Report -- " + sales.GetDate().ToString("yyyy-MM-dd"); PdfPage page = document.AddPage(); page.Size = PdfSharp.PageSize.A4; XUnit margin = XUnit.FromInch(1); XGraphics gfx = XGraphics.FromPdfPage(page); AddTitle(sales, margin, page, gfx); int pageNumber = 1; DrawPageNumber(pageNumber, margin, page, gfx); XUnit yCoord = margin + XUnit.FromInch(1.3); // draw headers DrawHeaders(yCoord, margin, gfx); XUnit xCoord = margin; XFont itemFont = new XFont("Segoe UI", 14, XFontStyle.Regular); XFont itemDescriptionFont = new XFont("Segoe UI", 12, XFontStyle.Regular); //for (int i = 0; i < 40; i++) // for creating lots of PDF dummy data //{ foreach (ReportItemSold itemSold in sales.GetItemsSold()) { if (yCoord + XUnit.FromInch(0.6) >= page.Height - margin) { page = document.AddPage(); page.Size = PdfSharp.PageSize.A4; gfx = XGraphics.FromPdfPage(page); AddTitle(sales, margin, page, gfx); DrawPageNumber(++pageNumber, margin, page, gfx); yCoord = margin + XUnit.FromInch(1.3); DrawHeaders(yCoord, margin, gfx); } yCoord += XUnit.FromInch(0.5); xCoord = margin; // these could be centered nicely or something, but *shrug* if (string.IsNullOrWhiteSpace(itemSold.Description)) { gfx.DrawString(itemSold.Name, itemFont, XBrushes.Black, new XRect(xCoord, yCoord, XUnit.FromInch(0), XUnit.FromInch(0.25)), XStringFormats.CenterLeft); } else { gfx.DrawString(itemSold.Name, itemFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); gfx.DrawString(itemSold.Description, itemDescriptionFont, XBrushes.Black, new XPoint(xCoord, yCoord + XUnit.FromInch(0.25)), XStringFormats.CenterLeft); } xCoord += XUnit.FromInch(2.5); gfx.DrawString(itemSold.QuantityPurchased.ToString(), itemFont, XBrushes.Black, new XRect(xCoord + XUnit.FromInch(0.65), yCoord, XUnit.FromInch(0), XUnit.FromInch(.25)), XStringFormats.CenterRight); //new XPoint(xCoord + XUnit.FromInch(0.65), yCoord), XStringFormats.CenterRight); xCoord += XUnit.FromInch(1.5); gfx.DrawString(itemSold.TotalCostWithCurrency, itemFont, XBrushes.Black, //new XPoint(xCoord + XUnit.FromInch(0.85), yCoord), XStringFormats.CenterRight); new XRect(xCoord + XUnit.FromInch(0.85), yCoord, XUnit.FromInch(0), XUnit.FromInch(.25)), XStringFormats.CenterRight); xCoord += XUnit.FromInch(1.5); gfx.DrawString(itemSold.TotalProfitWithCurrency, itemFont, XBrushes.Black, //new XPoint(page.Width - margin - XUnit.FromInch(0.05), yCoord), XStringFormats.CenterRight); new XRect(page.Width - margin - XUnit.FromInch(0.05), yCoord, XUnit.FromInch(0), XUnit.FromInch(.25)), XStringFormats.CenterRight); XUnit yCoordForLine = XUnit.FromInch(0.38); gfx.DrawLine(XPens.Black, margin, yCoord + yCoordForLine, page.Width - margin, yCoord + yCoordForLine); } //} yCoord += XUnit.FromInch(0.15); // print category totals var itemTypeMoneyInfoList = sales.GetItemTypeMoneyInfo(); foreach (var moneyInfo in itemTypeMoneyInfoList) { if (yCoord + XUnit.FromInch(0.5) >= page.Height - margin) { // GOTTA AADDDDDD A NEWWWW PAGEEE.... page = document.AddPage(); page.Size = PdfSharp.PageSize.A4; gfx = XGraphics.FromPdfPage(page); AddTitle(sales, margin, page, gfx); DrawPageNumber(++pageNumber, margin, page, gfx); yCoord = margin + XUnit.FromInch(1.3); DrawHeaders(yCoord, margin, gfx); } yCoord += XUnit.FromInch(0.5); XFont totalCategoryFont = new XFont("Segoe UI", 14, XFontStyle.Bold); XFont totalCategoryDataFont = new XFont("Segoe UI", 14, XFontStyle.Bold); xCoord = margin; gfx.DrawString(moneyInfo.Type.Name + " total", totalCategoryFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); xCoord += XUnit.FromInch(2.5); gfx.DrawString(moneyInfo.TotalItemsSold.ToString(), totalCategoryDataFont, XBrushes.Black, new XPoint(xCoord + XUnit.FromInch(0.65), yCoord), XStringFormats.CenterRight); xCoord += XUnit.FromInch(1.5); gfx.DrawString(moneyInfo.TotalIncomeWithCurrency.ToString(), totalCategoryDataFont, XBrushes.Black, new XPoint(xCoord + XUnit.FromInch(0.85), yCoord), XStringFormats.CenterRight); xCoord += XUnit.FromInch(1.5); gfx.DrawString(moneyInfo.TotalProfitWithCurrency.ToString(), totalCategoryDataFont, XBrushes.Black, new XPoint(page.Width - margin - XUnit.FromInch(0.05), yCoord), XStringFormats.CenterRight); } // print totals if (yCoord + XUnit.FromInch(0.5) >= page.Height - margin) { // GOTTA AADDDDDD A NEWWWW PAGEEE.... page = document.AddPage(); page.Size = PdfSharp.PageSize.A4; gfx = XGraphics.FromPdfPage(page); AddTitle(sales, margin, page, gfx); DrawPageNumber(++pageNumber, margin, page, gfx); yCoord = margin + XUnit.FromInch(1.3); DrawHeaders(yCoord, margin, gfx); } yCoord += XUnit.FromInch(0.5); XFont totalFont = new XFont("Segoe UI", 16, XFontStyle.Bold); XFont totalDataFont = new XFont("Segoe UI", 14, XFontStyle.Bold); xCoord = margin; gfx.DrawString("TOTAL", totalFont, XBrushes.Black, new XPoint(xCoord, yCoord), XStringFormats.CenterLeft); xCoord += XUnit.FromInch(2.5); gfx.DrawString(sales.GetTotalItemsSold().ToString(), totalDataFont, XBrushes.Black, new XPoint(xCoord + XUnit.FromInch(0.65), yCoord), XStringFormats.CenterRight); xCoord += XUnit.FromInch(1.5); gfx.DrawString(sales.GetTotalIncomeWithCurrency(), totalDataFont, XBrushes.Black, new XPoint(xCoord + XUnit.FromInch(0.85), yCoord), XStringFormats.CenterRight); xCoord += XUnit.FromInch(1.5); gfx.DrawString(sales.GetTotalProfitWithCurrency(), totalDataFont, XBrushes.Black, new XPoint(page.Width - margin - XUnit.FromInch(0.05), yCoord), XStringFormats.CenterRight); // save the document and start the process for viewing the pdf document.Save(outputPath); Process.Start(outputPath); }
public static PdfDocument CreateDocument(IEnumerable <CardData> cards, DateTime fileChanged) { var pageWdith = XUnit.FromInch(2.5); var pageHeight = XUnit.FromInch(3.5); PdfDocument document = new PdfDocument(); document.Info.Title = "Forschungs Karten"; document.Info.Subject = "Die Forschungskarten des spiels"; document.Info.Author = "Arbeitstitel Karthago"; document.Info.Keywords = "Karten, Forschung, Karthago"; //var maxOccurenceOfCard = cards.Max(x => x.Metadata.Times); int counter = 0; var total = cards.Count(); foreach (var card in cards) { counter++; PdfPage page = document.AddPage(); page.Width = new XUnit(pageWdith.Millimeter, XGraphicsUnit.Millimeter); page.Height = new XUnit(pageHeight.Millimeter, XGraphicsUnit.Millimeter); XGraphics gfx = XGraphics.FromPdfPage(page); // HACK² gfx.MUH = PdfFontEncoding.Unicode; //gfx.MFEH = PdfFontEmbedding.Default; XFont font = new XFont("Verdana", 13, XFontStyle.Regular); var costSize = new XSize(new XUnit(23, XGraphicsUnit.Millimeter), font.Height); var costMarginRight = new XUnit(5, XGraphicsUnit.Millimeter); var costRect = new XRect(pageWdith - costSize.Width - costMarginRight, new XUnit(5, XGraphicsUnit.Millimeter), costSize.Width, costSize.Height); var actionRect = new XRect(costMarginRight, new XUnit(5, XGraphicsUnit.Millimeter), pageWdith - costMarginRight - costMarginRight, costSize.Height); var durationRect = costRect; durationRect.Height *= 2.1; gfx.DrawRoundedRectangle(XPens.RoyalBlue, XBrushes.LightBlue, actionRect, new XSize(10, 10)); gfx.DrawRoundedRectangle(XPens.Orange, XBrushes.LightYellow, durationRect, new XSize(10, 10)); gfx.DrawRoundedRectangle(XPens.Purple, XBrushes.MediumPurple, costRect, new XSize(10, 10)); var costTextRect = costRect; costTextRect.Width -= new XUnit(1, XGraphicsUnit.Millimeter); gfx.DrawString($"{card.Metadata.Cost:n0} ¤", font, XBrushes.Black, costTextRect, XStringFormats.CenterRight); var subfont = Markdown.GetSubstituteFont("⌛"); subfont = new XFont(subfont.Name, font.Size); var durationTextRect = durationRect; durationTextRect.Width -= new XUnit(1, XGraphicsUnit.Millimeter); gfx.DrawString($"{card.Metadata.Duration:n0} ⌛", subfont, XBrushes.Black, durationTextRect, XStringFormats.BottomRight); var actionTextRect = actionRect; actionTextRect.Offset(new XUnit(3, XGraphicsUnit.Millimeter), 0); gfx.DrawString($"Forschung", font, XBrushes.Black, actionTextRect, XStringFormats.CenterLeft); var dateRec = new XRect(new XUnit(3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter), new XUnit(3, XGraphicsUnit.Millimeter), new XUnit(3, XGraphicsUnit.Millimeter)); var dateFont = new XFont("Verdana", 7, XFontStyle.Regular); gfx.DrawString(fileChanged.ToString(), dateFont, XBrushes.Gray, dateRec.TopLeft); gfx.DrawString($"{counter}/{total}", dateFont, XBrushes.Gray, new XRect(0, 0, pageWdith - new XUnit(3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter)), XStringFormats.BottomRight); // Create a new MigraDoc document var doc = new Document(); doc.Info.Title = "Forschungs Karten"; doc.Info.Subject = "Die Forschungskarten des spiels"; doc.Info.Author = "Arbeitstitel Karthago"; doc.DefaultPageSetup.PageWidth = new Unit(pageWdith.Inch, UnitType.Inch); doc.DefaultPageSetup.PageHeight = new Unit(pageHeight.Inch, UnitType.Inch); doc.DefaultPageSetup.LeftMargin = new Unit(5, UnitType.Millimeter); doc.DefaultPageSetup.RightMargin = new Unit(5, UnitType.Millimeter); doc.DefaultPageSetup.BottomMargin = new Unit(10, UnitType.Millimeter); doc.DefaultPageSetup.TopMargin = new Unit(16, UnitType.Millimeter); doc.DefineStyles(); //Cover.DefineCover(document); //DefineTableOfContents(document); DefineContentSection(doc); card.Content.HandleBlocks(doc); // Create a renderer and prepare (=layout) the document MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc); docRenderer.PrepareDocument(); //XRect rect = new XRect(new XPoint(Unit.FromCentimeter(1).Value, Unit.FromCentimeter(3).Value), new XSize((pageWdith.Value - Unit.FromCentimeter(2).Value), (pageHeight.Value - Unit.FromCentimeter(4).Value))); // Use BeginContainer / EndContainer for simplicity only. You can naturaly use you own transformations. //XGraphicsContainer container = gfx.BeginContainer(rect, A4Rect, XGraphicsUnit.Point); // Draw page border for better visual representation //gfx.DrawRectangle(XPens.LightGray, A4Rect); // Render the page. Note that page numbers start with 1. docRenderer.RenderPage(gfx, 1); // Note: The outline and the hyperlinks (table of content) does not work in the produced PDF document. // Pop the previous graphical state //gfx.EndContainer(container); } // Back { PdfPage page = document.AddPage(); page.Width = new XUnit(pageWdith.Millimeter, XGraphicsUnit.Millimeter); page.Height = new XUnit(pageHeight.Millimeter, XGraphicsUnit.Millimeter); XGraphics gfx = XGraphics.FromPdfPage(page); // HACK² gfx.MUH = PdfFontEncoding.Unicode; //gfx.MFEH = PdfFontEmbedding.Default; XFont font = new XFont("Verdana", 30, XFontStyle.Regular); var costRect = new XRect(0, 0, page.Width, page.Height); gfx.DrawString($"Forschung", font, XBrushes.SkyBlue, costRect, XStringFormats.Center); } //DefineParagraphs(document); //DefineTables(document); //DefineCharts(document); return(document); }