Exemple #1
1
        /// <summary>
        /// Initializes a new instance of PdfTrueTypeFont from an XFont.
        /// </summary>
        public PdfTrueTypeFont(PdfDocument document, XFont font)
            : base(document)
        {
            Elements.SetName(Keys.Type, "/Font");
            Elements.SetName(Keys.Subtype, "/TrueType");

            // TrueType with WinAnsiEncoding only.
            OpenTypeDescriptor ttDescriptor = (OpenTypeDescriptor)FontDescriptorCache.GetOrCreateDescriptorFor(font);
            FontDescriptor = new PdfFontDescriptor(document, ttDescriptor);
            _fontOptions = font.PdfOptions;
            Debug.Assert(_fontOptions != null);

            //cmapInfo = new CMapInfo(null/*ttDescriptor*/);
            _cmapInfo = new CMapInfo(ttDescriptor);

            BaseFont = font.GlyphTypeface.GetBaseName();
     
            if (_fontOptions.FontEmbedding == PdfFontEmbedding.Always)
                BaseFont = PdfFont.CreateEmbeddedFontSubsetName(BaseFont);
            FontDescriptor.FontName = BaseFont;

            Debug.Assert(_fontOptions.FontEncoding == PdfFontEncoding.WinAnsi);
            if (!IsSymbolFont)
                Encoding = "/WinAnsiEncoding";

            Owner._irefTable.Add(FontDescriptor);
            Elements[Keys.FontDescriptor] = FontDescriptor.Reference;

            FontEncoding = font.PdfOptions.FontEncoding;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the page
            DrawPage(page);

            //set document info
            doc.DocumentInformation.Author = "Harry Hu";
            doc.DocumentInformation.Creator = "Harry Hu";
            doc.DocumentInformation.Keywords = "pdf, demo, document information";
            doc.DocumentInformation.Producer = "Spire.Pdf";
            doc.DocumentInformation.Subject = "Demo of Spire.Pdf";
            doc.DocumentInformation.Title = "Document Information";

            //file info
            doc.FileInfo.CrossReferenceType = PdfCrossReferenceType.CrossReferenceStream;
            doc.FileInfo.IncrementalUpdate = false;
            doc.FileInfo.Version = PdfVersion.Version1_5;

            //Save pdf file.
            doc.SaveToFile("Properties.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Properties.pdf");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();            

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the text
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            //Draw the image
            PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;

            page.Canvas.DrawImage(image, x, 60, width, height);

            //Save pdf file.
            doc.SaveToFile("Image.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Image.pdf");
        }
Exemple #4
0
 public void AttatchDocument(PdfDocument.DocumentHandle handle)
 {
     lo ck (_documentHandles)
     {
         _documentHandles.Add(handle);
     }
 }
        private void button1_Click(object sender, EventArgs e)
        {
            //load two document
            PdfDocument doc1 = new PdfDocument();
            doc1.LoadFromFile(@"..\..\..\..\..\..\Data\Sample1.pdf");

            PdfDocument doc2 = new PdfDocument();
            doc2.LoadFromFile(@"..\..\..\..\..\..\Data\Sample3.pdf");

            //Create page template
            PdfTemplate template = doc1.Pages[0].CreateTemplate();

            foreach (PdfPageBase page in doc2.Pages)
            {
                page.Canvas.SetTransparency(0.25f, 0.25f, PdfBlendMode.Overlay);
                page.Canvas.DrawTemplate(template, PointF.Empty);
            }

            //Save pdf file.
            doc2.SaveToFile("Overlay.pdf");
            doc1.Close();
            doc2.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Overlay.pdf");
        }
        public PdfDocument CreateRekenPyramide(string filename)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();
            int basislengte = 8;
            int maxbasisgetal = 14;

            Random rnd = new Random();
            for (int pyramide = 1; pyramide <= 3; pyramide++)
            {
                GeneratePyramid(basislengte, rnd, maxbasisgetal);

                int papierhoogte = ((int)page.Canvas.Size.Height / 3 - 40) * pyramide;

                TekenHelePyramideOpPapier(page, pyrArray, basislengte, papierhoogte);
            }
            //Save pdf file.
            doc.SaveToFile(filename);
            doc.Close();

            return doc;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            // Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            Image img = Image.FromFile(@"..\..\..\..\..\..\Data\Background.png");
            page.BackgroundImage = img;

            //Draw table
            DrawPage(page);

            //Save pdf file.
            doc.SaveToFile("ImageWaterMark.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("ImageWaterMark.pdf");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the page
            DrawPage(page);

            //set view reference
            doc.ViewerPreferences.CenterWindow = true;
            doc.ViewerPreferences.DisplayTitle = false;
            doc.ViewerPreferences.FitWindow = false;
            doc.ViewerPreferences.HideMenubar = true;
            doc.ViewerPreferences.HideToolbar = true;
            doc.ViewerPreferences.PageLayout = PdfPageLayout.SinglePage;

            //Save pdf file.
            doc.SaveToFile("ViewerPreference.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("ViewerPreference.pdf");
        }
    /// <summary>
    /// Checks whether the color mode of a document and a color match.
    /// </summary>
    public static XColor EnsureColorMode(PdfDocument document, XColor color)
    {
      if (document == null)
        throw new ArgumentNullException("document");

      return EnsureColorMode(document.Options.ColorMode, color);
    }
Exemple #10
0
        private void ParsePdf(DateTime curDate, byte[] pdfData)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromBytes(pdfData);

            Menus.Add(new Menu(curDate, doc.Pages[0].ExtractText()));
        }
Exemple #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PdfCatalog"/> class.
        /// </summary>
        public PdfCatalog(PdfDocument document)
            : base(document)
        {
            Elements.SetName(Keys.Type, "/Catalog");

            _version = "1.4";  // HACK in PdfCatalog
        }
Exemple #12
0
 public Stream GeneratePdfStream(string url)
 {
     var document = new PdfDocument { Url = url };
     var output = new PdfOutput {OutputStream = new MemoryStream()};
     PdfConvert.ConvertHtmlToPdf(document, output);
     output.OutputStream.Position = 0;
     return output.OutputStream;
 }
    internal PdfFormXObject(PdfDocument thisDocument, XForm form)
      : base(thisDocument)
    {
      Elements.SetName(Keys.Type, "/XObject");
      Elements.SetName(Keys.Subtype, "/Form");

      //if (form.IsTemplate)
      //{ }
    }
Exemple #14
0
        public override void WriteToPdf(PdfDocument doc)
        {
            // to do

            RectArea rect = new RectArea(PosX, PosY, Width, Height, false);
            rect.SetFillColor(0, 0, 0, 0);
            rect.SetStrokeColor(0, 0, 0, 250);
            rect.Stroked = true;
            rect.AddToDocument(doc);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PdfObjectStream"/> class.
        /// </summary>
        public PdfCrossReferenceStream(PdfDocument document)
            : base(document)
        {
#if DEBUG && CORE
            if (Internal.PdfDiagnostics.TraceXrefStreams)
            {
                Debug.WriteLine("PdfCrossReferenceStream created.");
            }
#endif
        }
Exemple #16
0
        // Reference: 3.4.6  Object Streams / Page 100

        /// <summary>
        /// Initializes a new instance of the <see cref="PdfObjectStream"/> class.
        /// </summary>
        public PdfObjectStream(PdfDocument document)
            : base(document)
        {
#if DEBUG && CORE
            if (Internal.PdfDiagnostics.TraceObjectStreams)
            {
                Debug.WriteLine("PdfObjectStream(document) created.");
            }
#endif
        }
 /// <summary>
 /// Initializes a new instance of this class with the document the objects are imported from.
 /// </summary>
 public PdfImportedObjectTable(PdfDocument owner, PdfDocument externalDocument)
 {
   if (owner == null)
     throw new ArgumentNullException("owner");
   if (externalDocument == null)
     throw new ArgumentNullException("externalDocument");
   this.owner = owner;
   this.externalDocumentHandle = externalDocument.Handle;
   this.xObjects = new PdfFormXObject[externalDocument.PageCount];
 }
        private async void LoadDocument()
        {
            LoadButton.IsEnabled = false;

            pdfDocument = null;
            Output.Source = null;
            PageNumberBox.Text = "1";
            RenderingPanel.Visibility = Visibility.Collapsed;

            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".pdf");
            StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                ProgressControl.Visibility = Visibility.Visible;
                try
                {
                    pdfDocument = await PdfDocument.LoadFromFileAsync(file, PasswordBox.Password);
                }
                catch (Exception ex)
                {
                    switch (ex.HResult)
                    {
                        case WrongPassword:
                            rootPage.NotifyUser("Document is password-protected and password is incorrect.", NotifyType.ErrorMessage);
                            break;

                        case GenericFail:
                            rootPage.NotifyUser("Document is not a valid PDF.", NotifyType.ErrorMessage);
                            break;

                        default:
                            // File I/O errors are reported as exceptions.
                            rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                            break;
                    }
                }

                if (pdfDocument != null)
                {
                    RenderingPanel.Visibility = Visibility.Visible;
                    if (pdfDocument.IsPasswordProtected)
                    {
                        rootPage.NotifyUser("Document is password protected.", NotifyType.StatusMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser("Document is not password protected.", NotifyType.StatusMessage);
                    }
                    PageCountText.Text = pdfDocument.PageCount.ToString();
                }
                ProgressControl.Visibility = Visibility.Collapsed;
            }
            LoadButton.IsEnabled = true;
        }
Exemple #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            // Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            
            float y = 10;

            //title
            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Categories List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Categories List", format1).Height;
            y = y + 5;

            RectangleF rctg = new RectangleF(new PointF(0, 0), page.Canvas.ClientSize);
            PdfLinearGradientBrush brush
                = new PdfLinearGradientBrush(rctg, Color.Navy, Color.OrangeRed, PdfLinearGradientMode.Vertical);
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            String formatted
                = "Beverages\nCondiments\nConfections\nDairy Products\nGrains/Cereals\nMeat/Poultry\nProduce\nSeafood";

            PdfList list = new PdfList(formatted);
            list.Font = font;
            list.Indent = 8;
            list.TextIndent = 5;
            list.Brush = brush;
            PdfLayoutResult result = list.Draw(page, 0, y);
            y = result.Bounds.Bottom;

            PdfSortedList sortedList = new PdfSortedList(formatted);
            sortedList.Font = font;
            sortedList.Indent = 8;
            sortedList.TextIndent = 5;
            sortedList.Brush = brush;
            sortedList.Draw(page, 0, y);

            //Save pdf file.
            doc.SaveToFile("SimpleList.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("SimpleList.pdf");
        }
        public PdfDocument CrearDocPDF(string rutaFichero, /*Usuario user,*/ Dictionary<string, List<Libro>> coleccionLibrosCarrito, string infoCookieLibros)
        {
            PdfDocument miFactura = new PdfDocument();

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;

            PdfPageSettings setting = new PdfPageSettings();
            setting.Size = PdfPageSize.A4;

            //String facturaHTML = File.ReadAllText(rutaFichero + "PlantillaFactura.html");
            String facturaHTML = GenerarFacturaEnHTML(rutaFichero + "Imagenes/", coleccionLibrosCarrito.Values.ElementAt(0), /*user,*/ infoCookieLibros);

            List<string> nombreKey = coleccionLibrosCarrito.Keys.ToList();
            string keyString = "";
            foreach (string key in nombreKey)
            {
                keyString = key;
                keyString = keyString.Replace('/', '_').Replace(' ', '_').Replace(':', '_');
            }

            Thread thread = new Thread(() =>
            {
                miFactura.LoadFromHTML(facturaHTML, false, setting, htmlLayoutFormat);
                //miFactura.LoadFromHTML(facturaHTML, false, true, true);
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //string filePath = rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf";

            //if (!File.Exists(filePath))
            //{
            //    FileStream f = File.Create(filePath);
            //    f.Close();
            //}
            try
            {
                //  miFactura.SaveToFile(rutaFichero + "Facturas/" + /*user.alias + keyString +*/ "Recibo.pdf");
                miFactura.SaveToFile("Recibo.pdf");
                mandar_email(miFactura);
            }
            catch (Exception e)
            {

            }


            //System.Diagnostics.Process.Start(rutaFichero + "facturas/" + user.loginUsuario + keyString + ".pdf");

            return miFactura;
        }
Exemple #21
0
        public void DetatchDocument(PdfDocument.DocumentHandle handle)
        {
            lo ck (_documentHandles)
            {
                // Notify other documents about detach
                int count = _documentHandles.Count;
                for (int idx = 0; idx < count; idx++)
                {
                    if (((PdfDocument.DocumentHandle)_documentHandles[idx]).IsAlive)
                    {
                        PdfDocument target = ((PdfDocument.DocumentHandle)_documentHandles[idx]).Target;
                        if (target != null)
                            target.OnExternalDocumentFinalized(handle);
                    }
                }

                // Clean up table
                for (int idx = 0; idx < _documentHandles.Count; idx++)
                {
                    PdfDocument target = ((PdfDocument.DocumentHandle)_documentHandles[idx]).Target;
                    if (target == null)
                    {
                        _documentHandles.RemoveAt(idx);
                        idx--;
                    }
                }
            }

            //lo ck (documents)
            //{
            //  int index = IndexOf(document);
            //  if (index != -1)
            //  {
            //    documents.RemoveAt(index);
            //    int count = documents.Count;
            //    for (int idx = 0; idx < count; idx++)
            //    {
            //      PdfDocument target = ((WeakReference)documents[idx]).Target as PdfDocument;
            //      if (target != null)
            //        target.OnExternalDocumentFinalized(document);
            //    }

            //    for (int idx = 0; idx < documents.Count; idx++)
            //    {
            //      PdfDocument target = ((WeakReference)documents[idx]).Target as PdfDocument;
            //      if (target == null)
            //      {
            //        documents.RemoveAt(idx);
            //        idx--;
            //      }
            //    }
            //  }
            //}
        }
    public PdfType0Font(PdfDocument document, XFont font, bool vertical)
      : base(document)
    {
      Elements.SetName(Keys.Type, "/Font");
      Elements.SetName(Keys.Subtype, "/Type0");
      Elements.SetName(Keys.Encoding, vertical ? "/Identity-V" : "/Identity-H");

      OpenTypeDescriptor ttDescriptor = (OpenTypeDescriptor)FontDescriptorStock.Global.CreateDescriptor(font);
      this.fontDescriptor = new PdfFontDescriptor(document, ttDescriptor);
      this.fontOptions = font.PdfOptions;
      Debug.Assert(this.fontOptions != null);

      this.cmapInfo = new CMapInfo(ttDescriptor);
      this.descendantFont = new PdfCIDFont(document, this.fontDescriptor, font);
      this.descendantFont.CMapInfo = this.cmapInfo;

      // Create ToUnicode map
      this.toUnicode = new PdfToUnicodeMap(document, this.cmapInfo);
      document.Internals.AddObject(toUnicode);
      Elements.Add(Keys.ToUnicode, toUnicode);

      //if (this.fontOptions.BaseFont != "")
      //{
      //  BaseFont = this.fontOptions.BaseFont;
      //}
      //else
      {
        BaseFont = font.Name.Replace(" ", "");
        switch (font.Style & (XFontStyle.Bold | XFontStyle.Italic))
        {
          case XFontStyle.Bold:
            this.BaseFont += ",Bold";
            break;

          case XFontStyle.Italic:
            this.BaseFont += ",Italic";
            break;

          case XFontStyle.Bold | XFontStyle.Italic:
            this.BaseFont += ",BoldItalic";
            break;
        }
      }
      // CID fonts are always embedded
      BaseFont = PdfFont.CreateEmbeddedFontSubsetName(BaseFont);

      this.fontDescriptor.FontName = BaseFont;
      this.descendantFont.BaseFont = BaseFont;

      PdfArray descendantFonts = new PdfArray(document);
      Owner.irefTable.Add(descendantFont);
      descendantFonts.Elements.Add(descendantFont.Reference);
      Elements[Keys.DescendantFonts] = descendantFonts;
    }
Exemple #23
0
        public void PrintOrder(MainViewModel model)
        {
            var reportStream =
                Assembly.GetExecutingAssembly().GetManifestResourceStream("HillStationPOS.Reports.Order.rdlc");

            var writer = new ReportWriter { ReportProcessingMode = ProcessingMode.Local };
            writer.DataSources.Clear();
            writer.DataSources.Add(new ReportDataSource { Name = "OrderItems", Value = model.OrderItems });
            writer.LoadReport(reportStream);

            var parameters = new List<ReportParameter>();
            foreach (var parameter in writer.GetParameters())
            {
                var param = new ReportParameter
                {
                    Prompt = parameter.Prompt,
                    Name = parameter.Name
                };
                switch (param.Name)
                {
                    case "OrderNumber":
                        param.Values.Add(model.OrderNumber);
                        break;

                    case "Address":
                        param.Values.Add(model.Address);
                        break;

                    default:
                        throw new InvalidEnumArgumentException(@"Invalid parameter name: " + param.Name);
                }
                parameters.Add(param);
            }

            writer.SetParameters(parameters);

            var stream = new MemoryStream();
            writer.Save(@"D:\Documents\xxx.pdf", WriterFormat.PDF);
            writer.Save(stream, WriterFormat.PDF);

            var pdf = new PdfDocument(stream);

            var size = pdf.Pages[0].Size;
            var paper = new PaperSize("Custom", (int)size.Width, (int)size.Height)
            {
                RawKind = (int)PaperKind.Custom
            };
            pdf.PageScaling = PdfPrintPageScaling.ActualSize;
            var printDocument = pdf.PrintDocument;
            //            printDocument.PrinterSettings.Copies = 2;
            printDocument.DefaultPageSettings.PaperSize = paper;

            //            printDocument.Print();
        }
        protected bool SavePDF(PdfDocument transferDetails)
        {
            if (File.Exists(Path.Combine(SieradzBankFilesPathHolder.TransferFilesPath, @"..\mBank\Transfers1.pdf")))
            {
                File.Open(Path.Combine(SieradzBankFilesPathHolder.TransferFilesPath, @"..\mBank\Transfers1.pdf"), FileMode.Open).Close();
                File.Delete(Path.Combine(SieradzBankFilesPathHolder.TransferFilesPath, @"..\mBank\Transfers1.pdf"));
            }
            transferDetails.SaveToFile(SieradzBankFilesPathHolder.TransferFilesPath + @"..\mBank\Transfers1.pdf",FileFormat.PDF);
            transferDetails.Close();

            return File.Exists(SieradzBankFilesPathHolder.TransferFilesPath + @"..\mBank\Transfers1.pdf");
        }
 /// <summary>
 /// Function to load the PDF file selected by the user
 /// </summary>
 /// <param name="pdfFile">StorageFile object of the selected PDF file</param>
 private async void LoadPDF(StorageFile pdfFile)
 {
     // Creating async operation to load the PDF file and render pages in zoomed-in and zoomed-out view
     // For password protected documents one needs to call the function as is, handle the exception 
     // returned from LoadFromFileAsync and then call it again by providing the appropriate document 
     // password.
     this.pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile);
     if (this.pdfDocument != null)
     {
         InitializeZoomedInView();
         InitializeZoomedOutView();
     }
 }
Exemple #26
0
        static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
            PdfPageBase page = document.Pages.Add();

            PdfPageBase page3 = document.Pages.Add();
            page3.Canvas.DrawString("Hello World2", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10);
            //save to PDF document
            document.Pages[1].Rotation = PdfPageRotateAngle.RotateAngle180;
            document.Pages.RemoveAt(0);
            document.SaveToFile("FromHTML.pdf", FileFormat.PDF);
            document.Close();
        }
Exemple #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one section
            PdfSection section = doc.Sections.Add();

            //Load image
            PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            float imageWidth = image.PhysicalDimension.Width / 2;
            float imageHeight = image.PhysicalDimension.Height / 2;
            foreach (PdfBlendMode mode in Enum.GetValues(typeof(PdfBlendMode)))
            {
                PdfPageBase page = section.Pages.Add();
                float pageWidth = page.Canvas.ClientSize.Width;
                float y = 0;

                //title
                y = y + 5;
                PdfBrush brush = new PdfSolidBrush(Color.OrangeRed);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Bold));
                PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
                String text = String.Format("Transparency Blend Mode: {0}", mode);
                page.Canvas.DrawString(text, font, brush, pageWidth / 2, y, format);
                SizeF size = font.MeasureString(text, format);
                y = y + size.Height + 6;

                page.Canvas.DrawImage(image, 0, y, imageWidth, imageHeight);
                page.Canvas.Save();
                float d = (page.Canvas.ClientSize.Width - imageWidth) / 5;
                float x = d;
                y = y + d / 2;
                for (int i = 0; i < 5; i++)
                {
                    float alpha = 1.0f / 6 * (5 - i);
                    page.Canvas.SetTransparency(alpha, alpha, mode);
                    page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight);
                    x = x + d;
                    y = y + d / 2;
                }
                page.Canvas.Restore();
            }

            //Save pdf file.
            doc.SaveToFile("Transparency.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Transparency.pdf");
        }
Exemple #28
0
 /// <summary>Marks object to be saved as indirect.</summary>
 /// <param name="document">a document the indirect reference will belong to.</param>
 /// <returns>object itself.</returns>
 public override PdfObject MakeIndirect(PdfDocument document)
 {
     return((iText.Kernel.Pdf.PdfNumber)base.MakeIndirect(document));
 }
        private void ReportFilm_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                using (MsSqlContext db = new MsSqlContext())
                {
                    var film = db.films.Include(c => c.Sessions).ToList();
                    var dest = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Отчёт по продажам билетов на фильм.pdf";
                    var file = new FileInfo(dest);
                    file.Directory.Create();
                    var pdf      = new PdfDocument(new PdfWriter(dest));
                    var document = new Document(pdf, PageSize.A2.Rotate());
                    var font     = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);

                    float[] columnWidths = { 10, 10, 10, 8 };
                    var     table        = new Table(UnitValue.CreatePercentArray(columnWidths));

                    var cell = new Cell(1, 4)
                               .Add(new Paragraph("Отчёт по фильмам"))
                               .SetFont(font)
                               .SetFontSize(13)
                               .SetFontColor(DeviceGray.WHITE)
                               .SetBackgroundColor(DeviceGray.BLACK)
                               .SetWidth(600)
                               .SetTextAlignment(TextAlignment.CENTER);
                    table.AddHeaderCell(cell);

                    Cell[] headerFooter =
                    {
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Фильм")),
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Количество сеансов")),
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Количество купленных билетов")),
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Общая сумма"))
                    };

                    foreach (var hfCell in headerFooter)
                    {
                        table.AddHeaderCell(hfCell);
                    }

                    int   Count_of_places = 0;
                    int   all_places      = 0;
                    float Summ_price      = 0;
                    for (int i = 0; i < film.Count; i++)
                    {
                        Summ_price = 0;
                        table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(film[i].film_name)));
                        table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph($"{film[i].Sessions.Count}")));
                        for (int f = 0; f <= film[i].Sessions.Count - 1; f++)
                        {
                            ICollection <sessions> sess = film[i].Sessions;
                            sessions buff_ses           = sess.ElementAt(f);
                            var      places_list        = db.places_list.Where(c => c.status == "Куплено").Where(c => c.sessionsId == buff_ses.Id).ToList();
                            Count_of_places = places_list.Count;
                            all_places      = all_places + Count_of_places;
                            Summ_price      = Count_of_places * buff_ses.price_of_tickets + Summ_price;
                        }
                        table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(all_places.ToString())));
                        table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(Summ_price.ToString())));
                        all_places = 0;
                    }
                    document.Add(table);
                    document.Close();
                    var p = new Process
                    {
                        StartInfo = new ProcessStartInfo(dest)
                        {
                            UseShellExecute = true
                        }
                    };
                    p.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #30
0
        public async Task PrintCheck(Order order, string path)
        {
            using (CarPartDbContext context = _contextFactory.CreateDbContext())
            {
                if (order == null)
                {
                    throw new Exception("Вы не выбрали заказ");
                }

                Address address = await context.Address.FirstOrDefaultAsync(x => x.Id == order.Id);

                order.Address = address;
                var orderParts = await context.Orders.Where(a => a.Id == order.Id)
                                 .Join(context.OrderParts,
                                       t => t.Id,
                                       x => x.OrderId,
                                       (t, x) => new { t, x })
                                 .Join(context.Parts,
                                       l => l.x.PartId,
                                       k => k.Id,
                                       (l, k) => new { l, k })
                                 .Join(context.PartProviders,
                                       d => d.l.x.PartId,
                                       m => m.PartId,
                                       (d, m) => new { d, m })
                                 .Join(context.Providers,
                                       z => z.m.ProviderId,
                                       u => u.Id,
                                       (z, u) => new
                {
                    PartId       = z.d.k.Id,
                    PartName     = z.d.k.Name,
                    PartColor    = z.d.k.Color,
                    PartInOrder  = z.d.l.x.AmountPart,
                    PartPrice    = z.d.l.x.Price,
                    PartProvider = z.m.ProviderId,
                    Provider     = u.Name
                }
                                       ).ToListAsync();

                using (PdfDocument document = new PdfDocument())
                {
                    double      price    = 0;
                    PdfPage     page     = document.Pages.Add();
                    PdfGraphics graphics = page.Graphics;
                    PdfFont     mainFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 14), true);
                    PdfFont     font     = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12), true);

                    graphics.DrawString("Магазин автозапчастей чек", font, PdfBrushes.Black, new PointF(200, 0));
                    graphics.DrawString($"Номер заказа: {order.Id}", mainFont, PdfBrushes.Black, new PointF(0, 25));
                    graphics.DrawString($"Дата создания заказа: {order.OrderCreationTime}", mainFont, PdfBrushes.Black, new PointF(0, 40));
                    graphics.DrawString($"Дата окончания заказа: {order.FinishDate}", mainFont, PdfBrushes.Black, new PointF(0, 55));
                    graphics.DrawString($"Статус: {order.Status}", mainFont, PdfBrushes.Black, new PointF(0, 70));
                    graphics.DrawString($"Адрес: г. {order.Address.City}, ул. {order.Address.Street} , {order.Address.House}-{order.Address.Apartament}", mainFont, PdfBrushes.Black, new PointF(0, 85));


                    PdfGrid   pdfGrid   = new PdfGrid();
                    DataTable dataTable = new DataTable();



                    dataTable.Columns.Add("Номер запчасти");
                    dataTable.Columns.Add("Имя");
                    dataTable.Columns.Add("Цвет");
                    dataTable.Columns.Add("Поставщик");
                    dataTable.Columns.Add("Всего");
                    dataTable.Columns.Add("Цена за единицу");

                    foreach (var p in orderParts)
                    {
                        dataTable.Rows.Add(new object[] { p.PartId, p.PartName, p.PartColor, p.Provider, p.PartInOrder, p.PartPrice });
                        price += p.PartInOrder * p.PartPrice;
                    }
                    PdfGridStyle gridStyle = new PdfGridStyle();
                    gridStyle.Font = font;
                    pdfGrid.Style  = gridStyle;

                    graphics.DrawString($"Итого: {price}", mainFont, PdfBrushes.Black, new PointF(0, 105));

                    pdfGrid.DataSource = dataTable;
                    pdfGrid.Draw(page, new PointF(0, 125));

                    document.Save(path);
                    document.Close(true);
                }
            }
        }
 /// <summary>Creates a PdfFormXObject with the barcode.</summary>
 /// <param name="foreground">The color of the pixels. It can be <c>null</c></param>
 /// <param name="document">The document</param>
 /// <returns>the XObject.</returns>
 public abstract PdfFormXObject CreateFormXObject(Color foreground, PdfDocument document);
Exemple #32
0
        /// <summary>
        /// Converte url para pdf (limitado apenas para uma página em formato A4)
        /// </summary>
        /// <param name="stringUrl">http://e.migalhas.com.br/payment/2020/03/25/SANTANDER_0236f0078_save.html</param>
        /// <param name="outputFile">byteArray de um pdf</param>
        /// <returns>string base 64 de um pdf</returns>
        public static string ConvertUrlToPdf(string stringUrl, out Byte[] outputFile)
        {
            PdfDocument         pdfDoc              = null;
            PdfPageSettings     pdfPageSetting      = null;
            PdfHtmlLayoutFormat pdfHtmlLayoutFormat = null;
            FileStream          fsOutput            = null;

            byte[] pdfByteArray   = null;
            string stringFilePath = null;
            Thread threadLoadHtml = null;

            try
            {
                pdfDoc = new PdfDocument();
                pdfDoc.ConvertOptions.SetPdfToHtmlOptions(true, true, 1);

                pdfPageSetting             = new PdfPageSettings();
                pdfPageSetting.Size        = PdfPageSize.A4;
                pdfPageSetting.Orientation = PdfPageOrientation.Portrait;
                pdfPageSetting.Margins     = new Spire.Pdf.Graphics.PdfMargins(10);

                pdfHtmlLayoutFormat           = new PdfHtmlLayoutFormat();
                pdfHtmlLayoutFormat.IsWaiting = false; //Não espera a leitura completa da url, se colocar true demora 30s para ler a url. :(
                pdfHtmlLayoutFormat.FitToPage = Clip.Width;
                pdfHtmlLayoutFormat.Layout    = Spire.Pdf.Graphics.PdfLayoutType.OnePage;

                //Faz a leitura em outra thread conforme documentação do componente Spire.Pdf
                threadLoadHtml = new Thread(() =>
                                            { pdfDoc.LoadFromHTML(stringUrl, false, false, false, pdfPageSetting, pdfHtmlLayoutFormat); });
                threadLoadHtml.SetApartmentState(ApartmentState.STA);
                threadLoadHtml.Start();
                threadLoadHtml.Join();

                stringFilePath = AppDomain.CurrentDomain.BaseDirectory + Guid.NewGuid().ToString() + ".pdf";

                fsOutput = new FileStream(stringFilePath, FileMode.CreateNew, FileAccess.ReadWrite);

                pdfDoc.SaveToStream(fsOutput, FileFormat.PDF);

                fsOutput.Close();                                 //Existe uma operação de io neste momento

                pdfByteArray = File.ReadAllBytes(stringFilePath); //Existe uma operação de io neste momento

                File.Delete(stringFilePath);                      //Existe uma operação de io neste momento

                pdfDoc.Close();

                outputFile = pdfByteArray;

                return(Convert.ToBase64String(pdfByteArray));
            }
            catch
            {
                throw; //em caso de erro, joga o erro pra cima
            }
            finally
            {
                pdfDoc              = null;
                pdfPageSetting      = null;
                pdfHtmlLayoutFormat = null;
                fsOutput            = null;
                pdfByteArray        = null;
                stringFilePath      = null;
                threadLoadHtml      = null;
            }
        }
Exemple #33
0
        /// <summary>
        /// Create ZugFerd Invoice Pdf
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public PdfDocument CreateZugFerdInvoicePDF(PdfDocument document)
        {
            //Add page to the PDF
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Create border color
            PdfColor borderColor = Syncfusion.Drawing.Color.FromArgb(255, 142, 170, 219);

            //Get the page width and height
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;

            //Set the header height
            float headerHeight = 90;


            PdfColor lightBlue      = Syncfusion.Drawing.Color.FromArgb(255, 91, 126, 215);
            PdfBrush lightBlueBrush = new PdfSolidBrush(lightBlue);

            PdfColor darkBlue      = Syncfusion.Drawing.Color.FromArgb(255, 65, 104, 209);
            PdfBrush darkBlueBrush = new PdfSolidBrush(darkBlue);

            PdfBrush whiteBrush = new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255));

#if COMMONSB
            Stream fontStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.arial.ttf");
#else
            Stream fontStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.arial.ttf");
#endif

            PdfTrueTypeFont headerFont = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);

            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 18, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);

            //Create string format.
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            float y = 0;
            float x = 0;

            //Set the margins of address.
            float margin = 30;

            //Set the line space
            float lineSpace = 7;

            PdfPen borderPen = new PdfPen(borderColor, 1f);

            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));


            PdfGrid grid = new PdfGrid();

            grid.DataSource = GetProductReport();

            #region Header

            //Fill the header with light Brush
            graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            string title = "INVOICE";

            SizeF textSize = headerFont.MeasureString(title);

            RectangleF headerTotalBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString(title, headerFont, whiteBrush, new RectangleF(0, 0, textSize.Width + 50, headerHeight), format);

            graphics.DrawRectangle(darkBlueBrush, headerTotalBounds);

            graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight + 10), format);

            arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);

            format.LineAlignment = PdfVerticalAlignment.Bottom;
            graphics.DrawString("Amount", arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight / 2 - arialRegularFont.Height), format);

            #endregion


            SizeF size = arialRegularFont.MeasureString("Invoice Number: 2058557939");
            y = headerHeight + margin;
            x = (pageWidth - margin) - size.Width;

            graphics.DrawString("Invoice Number: 2058557939", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            size = arialRegularFont.MeasureString("Date :" + DateTime.Now.ToString("dddd dd, MMMM yyyy"));
            x    = (pageWidth - margin) - size.Width;
            y   += arialRegularFont.Height + lineSpace;

            graphics.DrawString("Date: " + DateTime.Now.ToString("dddd dd, MMMM yyyy"), arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y = headerHeight + margin;
            x = margin;
            graphics.DrawString("Bill To:", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("Abraham Swearegin,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("United States, California, San Mateo,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9920 BridgePointe Parkway,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9365550136", arialRegularFont, PdfBrushes.Black, new PointF(x, y));


            #region Grid

            grid.Columns[0].Width = 110;
            grid.Columns[1].Width = 150;
            grid.Columns[2].Width = 110;
            grid.Columns[3].Width = 70;
            grid.Columns[4].Width = 100;

            for (int i = 0; i < grid.Headers.Count; i++)
            {
                grid.Headers[i].Height = 20;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;

                    pdfStringFormat.Alignment = PdfTextAlignment.Left;
                    if (j == 0 || j == 2)
                    {
                        grid.Headers[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }

                    grid.Headers[i].Cells[j].StringFormat = pdfStringFormat;

                    grid.Headers[i].Cells[j].Style.Font = arialBoldFont;
                }
                grid.Headers[0].Cells[0].Value = "Product Id";
            }
            for (int i = 0; i < grid.Rows.Count; i++)
            {
                grid.Rows[i].Height = 23;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;

                    pdfStringFormat.Alignment = PdfTextAlignment.Left;
                    if (j == 0 || j == 2)
                    {
                        grid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }

                    grid.Rows[i].Cells[j].StringFormat = pdfStringFormat;
                    grid.Rows[i].Cells[j].Style.Font   = arialRegularFont;
                }
            }
            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);
            grid.BeginCellLayout += Grid_BeginCellLayout;


            PdfGridLayoutResult result = grid.Draw(page, new PointF(0, y + 40));

            y                = result.Bounds.Bottom + lineSpace;
            format           = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;
            RectangleF bounds = new RectangleF(QuantityCellBounds.X, y, QuantityCellBounds.Width, QuantityCellBounds.Height);

            page.Graphics.DrawString("Grand Total:", arialBoldFont, PdfBrushes.Black, bounds, format);

            bounds = new RectangleF(TotalPriceCellBounds.X, y, TotalPriceCellBounds.Width, TotalPriceCellBounds.Height);
            page.Graphics.DrawString(GetTotalAmount(grid).ToString(), arialBoldFont, PdfBrushes.Black, bounds);


            #endregion



            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            graphics.DrawLine(borderPen, new PointF(0, pageHeight - 100), new PointF(pageWidth, pageHeight - 100));

            y = pageHeight - 100 + margin;

            size = arialRegularFont.MeasureString("800 Interchange Blvd.");

            x = pageWidth - size.Width - margin;

            graphics.DrawString("800 Interchange Blvd.", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y += arialRegularFont.Height + lineSpace;

            size = arialRegularFont.MeasureString("Suite 2501,  Austin, TX 78721");

            x = pageWidth - size.Width - margin;

            graphics.DrawString("Suite 2501,  Austin, TX 78721", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y += arialRegularFont.Height + lineSpace;

            size = arialRegularFont.MeasureString("Any Questions? [email protected]");

            x = pageWidth - size.Width - margin;
            graphics.DrawString("Any Questions? [email protected]", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            return(document);
        }
        public async Task <bool> Export(string path, ICollection <ScannedImage.Snapshot> snapshots, PdfSettings settings, OcrParams ocrParams, ProgressHandler progressCallback, CancellationToken cancelToken)
        {
            return(await Task.Factory.StartNew(() =>
            {
                var forced = appConfigManager.Config.ForcePdfCompat;
                var compat = forced == PdfCompat.Default ? settings.Compat : forced;

                var document = new PdfDocument();
                document.Info.Author = settings.Metadata.Author;
                document.Info.Creator = settings.Metadata.Creator;
                document.Info.Keywords = settings.Metadata.Keywords;
                document.Info.Subject = settings.Metadata.Subject;
                document.Info.Title = settings.Metadata.Title;

                if (settings.Encryption.EncryptPdf &&
                    (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
                {
                    document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                    if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                    {
                        document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                    }

                    if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                    {
                        document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                    }

                    document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                    document.SecuritySettings.PermitAnnotations = settings.Encryption.AllowAnnotations;
                    document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                    document.SecuritySettings.PermitExtractContent = settings.Encryption.AllowContentCopying;
                    document.SecuritySettings.PermitFormsFill = settings.Encryption.AllowFormFilling;
                    document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                    document.SecuritySettings.PermitModifyDocument = settings.Encryption.AllowDocumentModification;
                    document.SecuritySettings.PermitPrint = settings.Encryption.AllowPrinting;
                }

                IOcrEngine ocrEngine = null;
                if (ocrParams?.LanguageCode != null)
                {
                    var activeEngine = ocrManager.ActiveEngine;
                    if (activeEngine == null)
                    {
                        Log.Error("Supported OCR engine not installed.", ocrParams.LanguageCode);
                    }
                    else if (!activeEngine.CanProcess(ocrParams.LanguageCode))
                    {
                        Log.Error("OCR files not available for '{0}'.", ocrParams.LanguageCode);
                    }
                    else
                    {
                        ocrEngine = activeEngine;
                    }
                }

                var result = ocrEngine != null
                    ? BuildDocumentWithOcr(progressCallback, cancelToken, document, compat, snapshots, ocrEngine, ocrParams)
                    : BuildDocumentWithoutOcr(progressCallback, cancelToken, document, compat, snapshots);
                if (!result)
                {
                    return false;
                }

                var now = DateTime.Now;
                document.Info.CreationDate = now;
                document.Info.ModificationDate = now;
                if (compat == PdfCompat.PdfA1B)
                {
                    PdfAHelper.SetCidStream(document);
                    PdfAHelper.DisableTransparency(document);
                }

                if (compat != PdfCompat.Default)
                {
                    PdfAHelper.SetColorProfile(document);
                    PdfAHelper.SetCidMap(document);
                    PdfAHelper.CreateXmpMetadata(document, compat);
                }

                PathHelper.EnsureParentDirExists(path);
                document.Save(path);
                return true;
            }, TaskCreationOptions.LongRunning));
        }
        private bool BuildDocumentWithOcr(ProgressHandler progressCallback, CancellationToken cancelToken, PdfDocument document, PdfCompat compat, ICollection <ScannedImage.Snapshot> snapshots, IOcrEngine ocrEngine, OcrParams ocrParams)
        {
            var progress = 0;

            progressCallback(progress, snapshots.Count);

            var ocrPairs = new List <(PdfPage, Task <OcrResult>)>();

            // Step 1: Create the pages, draw the images, and start OCR
            foreach (var snapshot in snapshots)
            {
                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }

                var importedPdfPassThrough = snapshot.Source.FileFormat == null && !snapshot.TransformList.Any();

                PdfPage page;
                if (importedPdfPassThrough)
                {
                    page = CopyPdfPageToDoc(document, snapshot.Source);
                    if (PageContainsText(page))
                    {
                        // Since this page already contains text, don't use OCR
                        continue;
                    }
                }
                else
                {
                    page = document.AddPage();
                }

                var tempImageFilePath = Path.Combine(Paths.Temp, Path.GetRandomFileName());

                using (var stream = scannedImageRenderer.RenderToStream(snapshot).Result)
                    using (var img = XImage.FromStream(stream))
                    {
                        if (cancelToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (!importedPdfPassThrough)
                        {
                            DrawImageOnPage(page, img, compat);
                        }

                        if (cancelToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (!ocrRequestQueue.HasCachedResult(ocrEngine, snapshot, ocrParams))
                        {
                            img.GdiImage.Save(tempImageFilePath);
                        }
                    }

                if (cancelToken.IsCancellationRequested)
                {
                    File.Delete(tempImageFilePath);
                    break;
                }

                // Start OCR
                var ocrTask = ocrRequestQueue.QueueForeground(ocrEngine, snapshot, tempImageFilePath, ocrParams, cancelToken);
                ocrTask.ContinueWith(task =>
                {
                    // This is the best place to put progress reporting
                    // Long-running OCR is done, and drawing text on the page (step 2) is very fast
                    if (!cancelToken.IsCancellationRequested)
                    {
                        Interlocked.Increment(ref progress);
                        progressCallback(progress, snapshots.Count);
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);
                // Record the page and task for step 2
                ocrPairs.Add((page, ocrTask));
            }

            // Step 2: Wait for all the OCR results, and draw the text on each page
            foreach (var(page, ocrTask) in ocrPairs)
            {
                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }
                if (ocrTask.Result == null)
                {
                    continue;
                }
                DrawOcrTextOnPage(page, ocrTask.Result);
            }

            return(!cancelToken.IsCancellationRequested);
        }
        private bool BuildDocumentWithoutOcr(ProgressHandler progressCallback, CancellationToken cancelToken, PdfDocument document, PdfCompat compat, ICollection <ScannedImage.Snapshot> snapshots)
        {
            var progress = 0;

            progressCallback(progress, snapshots.Count);
            foreach (var snapshot in snapshots)
            {
                var importedPdfPassThrough = snapshot.Source.FileFormat == null && !snapshot.TransformList.Any();

                if (importedPdfPassThrough)
                {
                    CopyPdfPageToDoc(document, snapshot.Source);
                }
                else
                {
                    using (var stream = scannedImageRenderer.RenderToStream(snapshot).Result)
                        using (var img = XImage.FromStream(stream))
                        {
                            if (cancelToken.IsCancellationRequested)
                            {
                                return(false);
                            }

                            var page = document.AddPage();
                            DrawImageOnPage(page, img, compat);
                        }
                }
                progress++;
                progressCallback(progress, snapshots.Count);
            }
            return(true);
        }
Exemple #37
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string[] texts = new string[]
            {
                // International version of the text in English.
                "English\n" +
                "PDFsharp is a .NET library for creating and processing PDF documents 'on the fly'. " +
                "The library is completely written in C# and based exclusively on safe, managed code. " +
                "PDFsharp offers two powerful abstraction levels to create and process PDF documents.\n" +
                "For drawing text, graphics, and images there is a set of classes which are modeled similar to the classes " +
                "of the name space System.Drawing of the .NET framework. With these classes it is not only possible to create " +
                "the content of PDF pages in an easy way, but they can also be used to draw in a window or on a printer.\n" +
                "Additionally PDFsharp completely models the structure elements PDF is based on. With them existing PDF documents " +
                "can be modified, merged, or split with ease.\n" +
                "The source code of PDFsharp is Open Source under the MIT license (http://en.wikipedia.org/wiki/MIT_License). " +
                "Therefore it is possible to use PDFsharp without limitations in non open source or commercial projects/products.",

                // PDFsharp is 'Made in Germany'.
                "German (deutsch)\n" +
                "PDFsharp ist eine .NET-Bibliothek zum Erzeugen und Verarbeiten von PDF-Dokumenten 'On the Fly'. " +
                "Die Bibliothek ist vollständig in C# geschrieben und basiert ausschließlich auf sicherem, verwaltetem Code. " +
                "PDFsharp bietet zwei leistungsstarke Abstraktionsebenen zur Erstellung und Verarbeitung von PDF-Dokumenten.\n" +
                "Zum Zeichnen von Text, Grafik und Bildern gibt es einen Satz von Klassen, die sehr stark an die Klassen " +
                "des Namensraums System.Drawing des .NET Frameworks angelehnt sind. Mit diesen Klassen ist es nicht " +
                "nur auf einfache Weise möglich, den Inhalt von PDF-Seiten zu gestalten, sondern sie können auch zum " +
                "Zeichnen in einem Fenster oder auf einem Drucker verwendet werden.\n" +
                "Zusätzlich modelliert PDFsharp vollständig die Stukturelemente, auf denen PDF basiert. Dadurch können existierende " +
                "PDF-Dokumente mit Leichtigkeit zerlegt, ergänzt oder umgebaut werden.\n" +
                "Der Quellcode von PDFsharp ist Open-Source unter der MIT-Lizenz (http://de.wikipedia.org/wiki/MIT-Lizenz). " +
                "Damit kann PDFsharp auch uneingeschränkt in Nicht-Open-Source- oder kommerziellen Projekten/Produkten eingesetzt werden.",

                // Greek version.
                // The text was translated by Babel Fish. We here in Germany have no idea what it means.
                // If you are a native speaker please correct it and mail it to mailto:[email protected]
                "Greek (Translated with Babel Fish)\n" +
                "Το PDFsharp είναι βιβλιοθήκη δικτύου α. για τη δημιουργία και την επεξεργασία των εγγράφων PDF 'σχετικά με τη μύγα'. " +
                "Η βιβλιοθήκη γράφεται εντελώς γ # και βασίζεται αποκλειστικά εκτός από, διοικούμενος κώδικας. " +
                "Το PDFsharp προσφέρει δύο ισχυρά επίπεδα αφαίρεσης για να δημιουργήσει και να επεξεργαστεί τα έγγραφα PDF. " +
                "Για το κείμενο, τη γραφική παράσταση, και τις εικόνες σχεδίων υπάρχει ένα σύνολο κατηγοριών που διαμορφώνονται " +
                "παρόμοιος με τις κατηγορίες του διαστημικού σχεδίου συστημάτων ονόματος του. πλαισίου δικτύου. " +
                "Με αυτές τις κατηγορίες που είναι όχι μόνο δυνατό να δημιουργηθεί το περιεχόμενο των σελίδων PDF με έναν εύκολο " +
                "τρόπο, αλλά αυτοί μπορεί επίσης να χρησιμοποιηθεί για να επισύρει την προσοχή σε ένα παράθυρο ή σε έναν εκτυπωτή. " +
                "Επιπλέον PDFsharp διαμορφώνει εντελώς τα στοιχεία PDF δομών είναι βασισμένο. Με τους τα υπάρχοντα έγγραφα PDF " +
                "μπορούν να τροποποιηθούν, συγχωνευμένος, ή να χωρίσουν με την ευκολία. Ο κώδικας πηγής PDFsharp είναι ανοικτή πηγή " +
                "με άδεια MIT (http://en.wikipedia.org/wiki/MIT_License). Επομένως είναι δυνατό να χρησιμοποιηθεί PDFsharp χωρίς " +
                "προβλήματα στη μη ανοικτή πηγή ή τα εμπορικά προγράμματα/τα προϊόντα.",

                // Russian version (by courtesy of Alexey Kuznetsov).
                "Russian\n" +
                "PDFsharp это .NET библиотека для создания и обработки PDF документов 'налету'. " +
                "Библиотека полностью написана на языке C# и базируется исключительно на безопасном, управляемом коде. " +
                "PDFsharp использует два мощных абстрактных уровня для создания и обработки PDF документов.\n" +
                "Для рисования текста, графики, и изображений в ней используется набор классов, которые разработаны аналогично с" +
                "пакетом System.Drawing, библиотеки .NET framework. С помощью этих классов возможно не только создавать" +
                "содержимое PDF страниц очень легко, но они так же позволяют рисовать напрямую в окне приложения или на принтере.\n" +
                "Дополнительно PDFsharp имеет полноценные модели структурированных базовых элементов PDF. Они позволяют работать с существующим PDF документами " +
                "для изменения их содержимого, склеивания документов, или разделения на части.\n" +
                "Исходный код PDFsharp библиотеки это Open Source распространяемый под лицензией MIT (http://ru.wikipedia.org/wiki/MIT_License). " +
                "Теоретически она позволяет использовать PDFsharp без ограничений в не open source проектах или коммерческих проектах/продуктах.",

                // French version (by courtesy of Olivier Dalet).
                "French (Français)\n" +
                "PDFSharp est une librairie .NET permettant de créer et de traiter des documents PDF 'à la volée'. " +
                "La librairie est entièrement écrite en C# et exclusivement basée sur du code sûr et géré. " +
                "PDFSharp fournit deux puissants niveaux d'abstraction pour la création et le traitement des documents PDF.\n" +
                "Un jeu de classes, modélisées afin de ressembler aux classes du namespace System.Drawing du framework .NET, " +
                "permet de dessiner du texte, des graphiques et des images. Non seulement ces classes permettent la création du " +
                "contenu des pages PDF de manière aisée, mais elles peuvent aussi être utilisées pour dessiner dans une fenêtre ou pour l'imprimante.\n" +
                "De plus, PDFSharp modélise complètement les éléments structurels de PDF. Ainsi, des documents PDF existants peuvent être " +
                "facilement modifiés, fusionnés ou éclatés.\n" +
                "Le code source de PDFSharp est Open Source sous licence MIT (http://fr.wikipedia.org/wiki/Licence_MIT). " +
                "Il est donc possible d'utiliser PDFSharp sans limitation aucune dans des projets ou produits non Open Source ou commerciaux.",

                // Dutch version (by giCalle)
                "Dutch\n" +
                "PDFsharp is een .NET bibliotheek om PDF documenten te creëren en te verwerken. " +
                "De bibliotheek is volledig geschreven in C# en gebruikt uitsluitend veilige, 'managed code'. " +
                "PDFsharp biedt twee krachtige abstractie niveaus aan om PDF documenten te maken en te verwerken.\n" +
                "Om tekst, beelden en foto's weer te geven zijn er een reeks klassen beschikbaar, gemodelleerd naar de klassen " +
                "uit de 'System.Drawing' naamruimte van het .NET framework. Met behulp van deze klassen is het niet enkel mogelijk " +
                "om de inhoud van PDF pagina's aan te maken op een eenvoudige manier, maar ze kunnen ook gebruikt worden om dingen " +
                "weer te geven in een venster of naar een printer. Daarbovenop implementeert PDFsharp de volledige elementen structuur " +
                "waarop PDF is gebaseerd. Hiermee kunnen bestaande PDF documenten eenvoudig aangepast, samengevoegd of opgesplitst worden.\n" +
                "De broncode van PDFsharp is opensource onder een MIT licentie (http://nl.wikipedia.org/wiki/MIT-licentie). " +
                "Daarom is het mogelijk om PDFsharp te gebruiken zonder beperkingen in niet open source of commerciële projecten/producten.",

                // Danish version (by courtesy of Mikael Lyngvig).
                "Danish (Dansk)\n" +
                "PDFsharp er et .NET bibliotek til at dynamisk lave og behandle PDF dokumenter. " +
                "Biblioteket er skrevet rent i C# og indeholder kun sikker, managed kode. " +
                "PDFsharp tilbyder to stærke abstraktionsniveauer til at lave og behandle PDF dokumenter. " +
                "Til at tegne tekst, grafik og billeder findes der et sæt klasser som er modelleret ligesom klasserne i navnerummet " +
                "System.Drawing i .NET biblioteket. Med disse klasser er det ikke kun muligt at udforme indholdet af PDF siderne på en " +
                "nem måde – de kan også bruges til at tegne i et vindue eller på en printer. " +
                "Derudover modellerer PDFsharp fuldstændigt strukturelementerne som PDF er baseret på. " +
                "Med dem kan eksisterende PDF dokumenter nemt modificeres, sammenknyttes og adskilles. " +
                "Kildekoden til PDFsharp er Open Source under MIT licensen (http://da.wikipedia.org/wiki/MIT-Licensen). " +
                "Derfor er det muligt at bruge PDFsharp uden begrænsninger i både lukkede og kommercielle projekter og produkter.",

                // Portuguese version (by courtesy of Luís Rodrigues).
                "Portuguese (Português)\n" +
                "PDFsharp é uma biblioteca .NET para a criação e processamento de documentos PDF 'on the fly'." +
                "A biblioteca é completamente escrita em C# e baseada exclusivamente em código gerenciado e seguro. " +
                "O PDFsharp oferece dois níveis de abstração poderosa para criar e processar documentos PDF.\n" +
                "Para desenhar texto, gráficos e imagens, há um conjunto de classes que são modeladas de forma semelhante às classes " +
                "do espaço de nomes System.Drawing do framework .NET. Com essas classes não só é possível criar " +
                "o conteúdo das páginas PDF de uma maneira fácil, mas podem também ser usadas para desenhar numa janela ou numa impressora.\n" +
                "Adicionalmente, o PDFSharp modela completamente a estrutura dos elementos em que o PDF é baseado. Com eles, documentos PDF existentes " +
                "podem ser modificados, unidos, ou divididos com facilidade.\n" +
                "O código fonte do PDFsharp é Open Source sob a licença MIT (http://en.wikipedia.org/wiki/MIT_License). " +
                "Por isso, é possível usar o PDFsharp sem limitações em projetos/produtos não open source ou comerciais.",

                // Polish version (by courtesy of Krzysztof Jędryka)
                "Polish (polski)\n" +
                "PDFsharp jest  biblioteką .NET umożliwiającą tworzenie i przetwarzanie dokumentów PDF 'w locie'. " +
                "Biblioteka ta została stworzona w całości w języku C# i jest oparta wyłącznie na bezpiecznym i zarządzanym kodzie. " +
                "PDFsharp oferuje dwa rozbudowane poziomy abstrakcji do tworzenia i przetwarzania dokumentów PDF.\n" +
                "Do rysowania tekstu, grafiki i obrazów stworzono zbiór klas projektowanych na wzór klas przestrzeni nazw System.Drawing" +
                "platformy .NET. Z pomocą tych klas można tworzyć w wygodny sposób nie tylko zawartość stron dokumentu PDF, ale można również" +
                "rysować w oknie programu lub generować wydruki.\n" +
                "Ponadto PDFsharp w pełni odwzorowuje strukturę elementów na których opiera się format pliku PDF." +
                "Używając tych elementów, dokumenty PDF można modyfikować, łączyć lub dzielić z łatwością.\n" +
                "Kod źródłowy PDFsharp jest dostępny na licencji Open Source MIT (http://pl.wikipedia.org/wiki/Licencja_MIT). " +
                "Zatem można korzystać z PDFsharp bez żadnych ograniczeń w projektach niedostępnych dla społeczności Open Source lub komercyjnych.",


                // Your language may come here.
                "Invitation\n" +
                "If you use PDFsharp and haven't found your native language in this document, we will be pleased to get your translation of the text above and include it here.\n" +
                "Mail to [email protected]"
            };

            // Create new document
            PdfDocument document = new PdfDocument();

            // Set font encoding to unicode
            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

            XFont font = new XFont("Times New Roman", 12, XFontStyle.Regular, options);

            // Draw text in different languages
            for (int idx = 0; idx < texts.Length; idx++)
            {
                PdfPage        page = document.AddPage();
                XGraphics      gfx  = XGraphics.FromPdfPage(page);
                XTextFormatter tf   = new XTextFormatter(gfx);
                tf.Alignment = XParagraphAlignment.Left;

                tf.DrawString(texts[idx], font, XBrushes.Black,
                              new XRect(100, 100, page.Width - 200, 600), XStringFormats.TopLeft);
            }

            const string filename = "Unicode_tempfile.pdf";

            // Save the document...
            document.Save(filename);
            // ...and start a viewer.
            // Process.Start(filename);
        }
Exemple #38
0
 /// <summary>Copies object to a specified document.</summary>
 /// <remarks>
 /// Copies object to a specified document.
 /// Works only for objects that are read from existing document, otherwise an exception is thrown.
 /// </remarks>
 /// <param name="document">document to copy object to.</param>
 /// <param name="allowDuplicating">
 /// indicates if to allow copy objects which already have been copied.
 /// If object is associated with any indirect reference and allowDuplicating is false then already existing reference will be returned instead of copying object.
 /// If allowDuplicating is true then object will be copied and new indirect reference will be assigned.
 /// </param>
 /// <returns>copied object.</returns>
 public override PdfObject CopyTo(PdfDocument document, bool allowDuplicating)
 {
     return((iText.Kernel.Pdf.PdfNumber)base.CopyTo(document, allowDuplicating));
 }
Exemple #39
0
 /// <summary>Copies object to a specified document.</summary>
 /// <remarks>
 /// Copies object to a specified document.
 /// Works only for objects that are read from existing document, otherwise an exception is thrown.
 /// </remarks>
 /// <param name="document">document to copy object to.</param>
 /// <returns>copied object.</returns>
 public override PdfObject CopyTo(PdfDocument document)
 {
     return((iText.Kernel.Pdf.PdfNumber)base.CopyTo(document, true));
 }
Exemple #40
0
 /// <summary>Marks object to be saved as indirect.</summary>
 /// <param name="document">a document the indirect reference will belong to.</param>
 /// <returns>object itself.</returns>
 public override PdfObject MakeIndirect(PdfDocument document, PdfIndirectReference reference)
 {
     return((iText.Kernel.Pdf.PdfNumber)base.MakeIndirect(document, reference));
 }
Exemple #41
0
            internal virtual void ProcessPage(PdfDocument pdfDoc, int pageNumber)
            {
                PageContextProcessor pageProcessor = htmlDocumentRenderer.GetPageProcessor(pageNumber);

                pageProcessor.ProcessPageEnd(pageNumber, pdfDoc, htmlDocumentRenderer);
            }
Exemple #42
0
        public void TestRenderingAllSamples()
        {
            string path = "SampleXpsDocuments_1_0";
            string dir  = (path);

            if (dir == null)
            {
                Assert.Inconclusive("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");
                return;
            }
            if (!Directory.Exists(dir))
            {
                Assert.Inconclusive("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");
                return;
            }
#if true
            string[] files = Directory.GetFiles(dir, "*.xps", SearchOption.AllDirectories);
#else
            string[] files = Directory.GetFiles("../../../XPS-TestDocuments", "*.xps", SearchOption.AllDirectories);
#endif
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\MXDW", "*.xps", SearchOption.AllDirectories);
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\Handcrafted", "*.xps", SearchOption.AllDirectories);
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\Showcase", "*.xps", SearchOption.AllDirectories);
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\QualityLogicMinBar", "*.xps", SearchOption.AllDirectories);


            if (files.Length == 0)
            {
                Assert.Inconclusive("No sample file found. Copy sample files to the \"SampleXpsDocuments_1_0\" folder!");
                return;
            }

            foreach (string filename in files)
            {
                // No negative tests here
                if (filename.Contains("\\ConformanceViolations\\"))
                {
                    continue;
                }

                //if (filename.Contains("\\Showcase\\"))
                //  continue;

                //if (!filename.Contains("Vista"))
                //  continue;

                Debug.WriteLine(filename);
                try
                {
                    int         docIndex = 0;
                    XpsDocument xpsDoc   = XpsDocument.Open(filename);
                    foreach (FixedDocument doc in xpsDoc.Documents)
                    {
                        try
                        {
                            PdfDocument pdfDoc   = new PdfDocument();
                            PdfRenderer renderer = new PdfRenderer();

                            int pageIndex = 0;
                            foreach (FixedPage page in doc.Pages)
                            {
                                if (page == null)
                                {
                                    continue;
                                }
                                Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));
                                PdfPage pdfPage = renderer.CreatePage(pdfDoc, page);
                                renderer.RenderPage(pdfPage, page);
                                pageIndex++;

                                // stop at page...
                                if (pageIndex == 50)
                                {
                                    break;
                                }
                            }

                            string pdfFilename = IOPath.GetFileNameWithoutExtension(filename);
                            if (docIndex != 0)
                            {
                                pdfFilename += docIndex.ToString();
                            }
                            pdfFilename += ".pdf";
                            pdfFilename  = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename);

                            pdfDoc.Save(pdfFilename);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception: " + ex.Message);
                        }
                        docIndex++;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    GetType();
                }
            }
        }
Exemple #43
0
 public PdfCIDFont(PdfDocument document)
     : base(document)
 {
 }
Exemple #44
0
        public ActionResult JobApplication(string Browser)
        {
            PdfDocument pdfDoc = new PdfDocument();

            pdfDoc.ViewerPreferences.HideMenubar  = true;
            pdfDoc.ViewerPreferences.HideWindowUI = true;
            pdfDoc.ViewerPreferences.HideToolbar  = true;
            pdfDoc.ViewerPreferences.FitWindow    = true;

            pdfDoc.ViewerPreferences.PageLayout = PdfPageLayout.SinglePage;
            pdfDoc.PageSettings.Orientation     = PdfPageOrientation.Portrait;
            pdfDoc.PageSettings.Margins.All     = 0;

            //To set coordinates to draw form fields
            RectangleF       bounds = new RectangleF(180, 65, 156, 15);
            PdfUnitConverter con    = new PdfUnitConverter();

            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";

            //Read the file
            FileStream file = new FileStream(dataPath + "Careers.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            PdfImage img = new PdfBitmap(file);

            //Set the page size
            SizeF pageSize = new SizeF(500, 310);

            pdfDoc.PageSettings.Height = pageSize.Height;
            pdfDoc.PageSettings.Width  = pageSize.Width;

            PdfFont pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);

            #region First Page
            pdfDoc.Pages.Add();

            PdfPage firstPage = pdfDoc.Pages[0];
            pdfDoc.Pages[0].Graphics.DrawImage(img, 0, 0, pageSize.Width, pageSize.Height);
            pdfDoc.Pages[0].Graphics.DrawString("General Information", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), 25, 40);
            pdfDoc.Pages[0].Graphics.DrawString("Education Grade", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), 25, 190);

            pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
            //Create fields in first page.
            pdfDoc.Pages[0].Graphics.DrawString("First Name:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 65);

            //Create text box for firstname.
            PdfTextBoxField textBoxField1 = new PdfTextBoxField(pdfDoc.Pages[0], "FirstName");
            textBoxField1.ToolTip = "First Name";
            PdfStandardFont font1 = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
            textBoxField1.Font        = font1;
            textBoxField1.BorderColor = new PdfColor(Color.Gray);
            textBoxField1.BorderStyle = PdfBorderStyle.Beveled;
            textBoxField1.Bounds      = bounds;
            pdfDoc.Form.Fields.Add(textBoxField1);

            pdfDoc.Pages[0].Graphics.DrawString("Last Name:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 83);

            //Set position to draw form fields
            bounds.Y = bounds.Y + 18;
            //Create text box for lastname.
            PdfTextBoxField textBoxField2 = new PdfTextBoxField(pdfDoc.Pages[0], "LastName");
            textBoxField2.ToolTip     = "Last Name";
            textBoxField2.Font        = font1;
            textBoxField2.BorderColor = new PdfColor(Color.Gray);
            textBoxField2.BorderStyle = PdfBorderStyle.Beveled;
            textBoxField2.Bounds      = bounds;
            pdfDoc.Form.Fields.Add(textBoxField2);

            pdfDoc.Pages[0].Graphics.DrawString("Email:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 103);

            //Set position to draw form fields
            bounds.Y = bounds.Y + 18;

            //Create text box for Email.
            PdfTextBoxField textBoxField3 = new PdfTextBoxField(pdfDoc.Pages[0], "Email");
            textBoxField3.ToolTip     = "Email id";
            textBoxField3.Font        = font1;
            textBoxField3.BorderColor = new PdfColor(Color.Gray);
            textBoxField3.BorderStyle = PdfBorderStyle.Beveled;
            textBoxField3.Bounds      = bounds;
            pdfDoc.Form.Fields.Add(textBoxField3);

            pdfDoc.Pages[0].Graphics.DrawString("Business Phone:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 123);

            //Set position to draw form fields
            bounds.Y = bounds.Y + 18;

            //Create text box for Business phone.
            PdfTextBoxField textBoxField4 = new PdfTextBoxField(pdfDoc.Pages[0], "Business");
            textBoxField4.ToolTip     = "Business phone";
            textBoxField4.Font        = font1;
            textBoxField4.BorderColor = new PdfColor(Color.Gray);
            textBoxField4.BorderStyle = PdfBorderStyle.Beveled;
            textBoxField4.Bounds      = bounds;
            pdfDoc.Form.Fields.Add(textBoxField4);

            pdfDoc.Pages[0].Graphics.DrawString("Which position are\nyou applying for?", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 143);

            //Create combo box for Position.
            #region Create ComboBox
            //Set position to draw Combo Box
            bounds.Y = bounds.Y + 24;

            PdfComboBoxField comboBox = new PdfComboBoxField(pdfDoc.Pages[0], "JobTitle");
            comboBox.Bounds      = bounds;
            comboBox.BorderWidth = 1;
            comboBox.BorderColor = new PdfColor(Color.Gray);
            comboBox.Font        = pdfFont;
            comboBox.ToolTip     = "Job Title";


            comboBox.Items.Add(new PdfListFieldItem("Development", "accounts"));
            comboBox.Items.Add(new PdfListFieldItem("Support", "advertise"));
            comboBox.Items.Add(new PdfListFieldItem("Documentation", "agri"));

            pdfDoc.Form.Fields.Add(comboBox);
            #endregion

            pdfDoc.Pages[0].Graphics.DrawString("Highest qualification", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 217);

            //Create Checkbox box.
            #region Create CheckBox
            pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 8);
            //Set position to draw Checkbox
            bounds.Y     = 239;
            bounds.X     = 25;
            bounds.Width = 10;

            bounds.Height = 10;

            // Create a Check Box
            PdfCheckBoxField chb = new PdfCheckBoxField(pdfDoc.Pages[0], "Adegree");

            chb.Font        = pdfFont;
            chb.ToolTip     = "degree";
            chb.Bounds      = bounds;
            chb.BorderColor = new PdfColor(Color.Gray);
            bounds.X       += chb.Bounds.Height + 10;

            pdfDoc.Pages[0].Graphics.DrawString("Associate degree", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
            bounds.X += 90;
            pdfDoc.Form.Fields.Add(chb);
            //Create a Checkbox
            chb             = new PdfCheckBoxField(pdfDoc.Pages[0], "Bdegree");
            chb.Font        = pdfFont;
            chb.Bounds      = bounds;
            chb.BorderColor = new PdfColor(Color.Gray);
            bounds.X       += chb.Bounds.Height + 10;

            pdfDoc.Pages[0].Graphics.DrawString("Bachelor degree", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);

            bounds.X += 90;
            pdfDoc.Form.Fields.Add(chb);
            //Create a Checkbox
            chb = new PdfCheckBoxField(pdfDoc.Pages[0], "college");

            chb.Font        = pdfFont;
            chb.ToolTip     = "college";
            chb.Bounds      = bounds;
            chb.BorderColor = new PdfColor(Color.Gray);

            bounds.X += chb.Bounds.Height + 10;

            pdfDoc.Pages[0].Graphics.DrawString("College", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);

            bounds.Y += 20;
            bounds.X  = 25;
            pdfDoc.Form.Fields.Add(chb);
            //Create a Checkbox
            chb = new PdfCheckBoxField(pdfDoc.Pages[0], "pg");

            chb.Font        = pdfFont;
            chb.Bounds      = bounds;
            chb.BorderColor = new PdfColor(Color.Gray);
            bounds.X       += chb.Bounds.Height + 10;

            pdfDoc.Pages[0].Graphics.DrawString("Post Graduate", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);

            bounds.X += 90;
            pdfDoc.Form.Fields.Add(chb);
            //Create a Checkbox
            chb = new PdfCheckBoxField(pdfDoc.Pages[0], "mba");

            chb.Font        = pdfFont;
            chb.Bounds      = bounds;
            chb.BorderColor = new PdfColor(Color.Gray);

            bounds.X += chb.Bounds.Height + 10;

            pdfDoc.Pages[0].Graphics.DrawString("MBA", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);

            pdfDoc.Form.Fields.Add(chb);
            #endregion

            # region Create Button
Exemple #45
0
        public ScannedImageSource Import(string filePath, ImportParams importParams, ProgressHandler progressCallback, CancellationToken cancelToken)
        {
            var source = new ScannedImageSource.Concrete();

            Task.Factory.StartNew(async() =>
            {
                if (cancelToken.IsCancellationRequested)
                {
                    source.Done();
                }

                int passwordAttempts = 0;
                bool aborted         = false;
                int i = 0;
                try
                {
                    PdfDocument document = PdfReader.Open(filePath, PdfDocumentOpenMode.Import, args =>
                    {
                        if (!pdfPasswordProvider.ProvidePassword(Path.GetFileName(filePath), passwordAttempts++, out args.Password))
                        {
                            args.Abort = true;
                            aborted    = true;
                        }
                    });
                    if (passwordAttempts > 0 &&
                        !document.SecuritySettings.HasOwnerPermissions &&
                        !document.SecuritySettings.PermitExtractContent)
                    {
                        errorOutput.DisplayError(string.Format(MiscResources.PdfNoPermissionToExtractContent, Path.GetFileName(filePath)));
                        source.Done();
                    }

                    var pages = importParams.Slice.Indices(document.PageCount)
                                .Select(index => document.Pages[index])
                                .TakeWhile(page =>
                    {
                        progressCallback(i++, document.PageCount);
                        return(!cancelToken.IsCancellationRequested);
                    });
                    if (document.Info.Creator != MiscResources.NAPS2 && document.Info.Author != MiscResources.NAPS2)
                    {
                        pdfRenderer.ThrowIfCantRender();
                        foreach (var page in pages)
                        {
                            source.Put(await ExportRawPdfPage(page, importParams));
                        }
                    }
                    else
                    {
                        foreach (var page in pages)
                        {
                            await GetImagesFromPage(page, importParams, source);
                        }
                    }
                }
                catch (ImageRenderException e)
                {
                    errorOutput.DisplayError(string.Format(MiscResources.ImportErrorNAPS2Pdf, Path.GetFileName(filePath)));
                    Log.ErrorException("Error importing PDF file.", e);
                }
                catch (Exception e)
                {
                    if (!aborted)
                    {
                        errorOutput.DisplayError(string.Format(MiscResources.ImportErrorCouldNot, Path.GetFileName(filePath)));
                        Log.ErrorException("Error importing PDF file.", e);
                    }
                }
                finally
                {
                    source.Done();
                }
            }, TaskCreationOptions.LongRunning);
            return(source);
        }
 /// <summary>Creates a PdfFormXObject with the barcode.</summary>
 /// <remarks>
 /// Creates a PdfFormXObject with the barcode.
 /// Default foreground color will be used.
 /// </remarks>
 /// <param name="document">The document</param>
 /// <returns>the XObject.</returns>
 public virtual PdfFormXObject CreateFormXObject(PdfDocument document)
 {
     return(CreateFormXObject(null, document));
 }
Exemple #47
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                //Getting Image files Path.
                string dataPath = Application.StartupPath + @"\..\..\..\..\..\..\..\Common\Images\DocIO\";

                //Getting text files Path.
                string dataPath1 = Application.StartupPath + @"\..\..\..\..\..\..\..\Common\Data\";

                //Creating a new document
                WordDocument document = new WordDocument();
                //Adding a new section.
                IWSection   section   = document.AddSection();
                IWParagraph paragraph = section.AddParagraph();
                paragraph = section.AddParagraph();
                section.PageSetup.Margins.All = 72f;
                IWTextRange text = paragraph.AppendText("Adventure products");
                //Formatting Text
                text.CharacterFormat.FontName = "Bitstream Vera Sans";
                text.CharacterFormat.FontSize = 12f;
                text.CharacterFormat.Bold     = true;
                section.AddParagraph();
                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.LineSpacing = 20f;
                paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group ");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;

                #region Line break
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
                #endregion

                section = document.AddSection();

                section.BreakCode             = SectionBreakCode.NoBreak;
                section.PageSetup.Margins.All = 72f;
                //Adding three columns to section.
                section.AddColumn(100, 15);
                section.AddColumn(100, 15);
                section.AddColumn(100, 15);
                //Set the columns to be of equal width.
                section.MakeColumnsEqual();

                //Adding a new paragraph to the section.
                paragraph = section.AddParagraph();
                //Adding text.
                text = paragraph.AppendText("Mountain-200");
                //Formatting Text
                text.CharacterFormat.FontName = "Bitstream Vera Sans";
                text.CharacterFormat.FontSize = 12f;
                text.CharacterFormat.Bold     = true;
                //Adding a new paragraph to the section.
                section.AddParagraph();
                paragraph = section.AddParagraph();
                //Inserting an Image.
                WPicture picture = paragraph.AppendPicture(new Bitmap(Path.Combine(dataPath, "Mountain-200.jpg"))) as WPicture;
                picture.Width  = 120f;
                picture.Height = 90f;
                //Adding a new paragraph to the section.
                section.AddParagraph();
                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.LineSpacing = 20f;
                //Adding text.
                paragraph.AppendText(@"Product No:BK-M68B-38" + "\n" + "Size: 38" + "\n" + "Weight: 25\n" + "Price: $2,294.99");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;

                // Set column break as true. It navigates the cursor position to the next Column.
                paragraph.ParagraphFormat.ColumnBreakAfter = true;

                paragraph = section.AddParagraph();
                text      = paragraph.AppendText("Mountain-300");
                text.CharacterFormat.FontName = "Bitstream Vera Sans";
                text.CharacterFormat.FontSize = 12f;
                text.CharacterFormat.Bold     = true;

                section.AddParagraph();
                paragraph      = section.AddParagraph();
                picture        = paragraph.AppendPicture(new Bitmap(Path.Combine(dataPath, "Mountain-300.jpg"))) as WPicture;
                picture.Width  = 120f;
                picture.Height = 90f;
                section.AddParagraph();
                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.LineSpacing = 20f;
                paragraph.AppendText(@"Product No:BK-M4-38" + "\n" + "Size: 35\n" + "Weight: 22" + "\n" + " Price: $1,079.99");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;

                paragraph.ParagraphFormat.ColumnBreakAfter = true;

                paragraph = section.AddParagraph();
                text      = paragraph.AppendText("Road-150");
                text.CharacterFormat.FontName = "Bitstream Vera Sans";
                text.CharacterFormat.FontSize = 12f;
                text.CharacterFormat.Bold     = true;

                section.AddParagraph();
                paragraph      = section.AddParagraph();
                picture        = paragraph.AppendPicture(new Bitmap(Path.Combine(dataPath, "Road-550-W.jpg"))) as WPicture;
                picture.Width  = 120f;
                picture.Height = 90f;
                section.AddParagraph();
                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.LineSpacing = 20f;
                paragraph.AppendText(@"Product No: BK-R93R-44" + "\n" + "Size: 44" + "\n" + "Weight: 14" + "\n" + "Price: $3,578.27");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;

                section                       = document.AddSection();
                section.BreakCode             = SectionBreakCode.NoBreak;
                section.PageSetup.Margins.All = 72f;

                text = section.AddParagraph().AppendText("First Look\n");
                //Formatting Text
                text.CharacterFormat.FontName = "Bitstream Vera Sans";
                text.CharacterFormat.FontSize = 12f;
                text.CharacterFormat.Bold     = true;

                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.LineSpacing = 20f;
                paragraph.AppendText("Adventure Works Cycles, the fictitious company, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
                paragraph.ParagraphFormat.PageBreakAfter      = true;

                paragraph = section.AddParagraph();
                text      = paragraph.AppendText("Introduction\n");
                //Formatting Text
                text.CharacterFormat.FontName = "Bitstream Vera Sans";
                text.CharacterFormat.FontSize = 12f;
                text.CharacterFormat.Bold     = true;
                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.LineSpacing = 20f;
                paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;

                //Save as doc format
                if (wordDocRadioBtn.Checked)
                {
                    //Saving the document to disk.
                    document.Save("Sample.doc");

                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.doc");
                        //Exit
                        this.Close();
                    }
                }
                //Save as docx format
                else if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.docx");
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start("Sample.pdf");
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Exemple #48
0
 public PDFUtils(byte[] pdf)
 {
     using (MemoryStream stream = new MemoryStream(pdf)) {
         document = PdfReader.Open(stream);
     }
 }
Exemple #49
0
        private bool IsEqualSameNameDestExist(IDictionary <PdfPage, PdfPage> page2page, PdfDocument toDocument, String
                                              srcDestName, PdfArray srcDestArray, PdfPage oldPage)
        {
            PdfArray sameNameDest = (PdfArray)toDocument.GetCatalog().GetNameTree(PdfName.Dests).GetNames().Get(srcDestName
                                                                                                                );
            bool equalSameNameDestExists = false;

            if (sameNameDest != null && sameNameDest.GetAsDictionary(0) != null)
            {
                PdfIndirectReference existingDestPageRef = sameNameDest.GetAsDictionary(0).GetIndirectReference();
                PdfIndirectReference newDestPageRef      = page2page.Get(oldPage).GetPdfObject().GetIndirectReference();
                if (equalSameNameDestExists = existingDestPageRef.Equals(newDestPageRef) && sameNameDest.Size() == srcDestArray
                                              .Size())
                {
                    for (int i = 1; i < sameNameDest.Size(); ++i)
                    {
                        equalSameNameDestExists = equalSameNameDestExists && sameNameDest.Get(i).Equals(srcDestArray.Get(i));
                    }
                }
            }
            return(equalSameNameDestExists);
        }
Exemple #50
0
        private async void Print_Clicked(object sender, EventArgs e)
        {
            #region Fields
            //Create border color
            PdfColor borderColor     = new PdfColor(Color.FromArgb(255, 51, 181, 75));
            PdfBrush lightGreenBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 218, 218, 221)));

            PdfBrush darkGreenBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 51, 181, 75)));

            PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 255, 255, 255)));
            PdfPen   borderPen  = new PdfPen(borderColor, 1f);
            Stream   fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf");
            //Create TrueType font
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 11, PdfFontStyle.Bold);


            const float margin       = 30;
            const float lineSpace    = 7;
            const float headerHeight = 90;
            #endregion

            #region header and buyer infomation
            //Create PDF with PDF/A-3b conformance
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
            //Set ZUGFeRD profile
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;

            //Add page to the PDF
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Get the page width and height
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;
            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Fill the header with light Brush
            graphics.DrawRectangle(lightGreenBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString("INVOICE", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3));
            Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.ic_launcher.png");

            //Create a new PdfBitmap instance
            PdfBitmap image = new PdfBitmap(imageStream);

            //Draw the image
            graphics.DrawImage(image, new PointF(margin + 90, headerAmountBounds.Height / 2));
            graphics.DrawRectangle(darkGreenBrush, headerAmountBounds);

            graphics.DrawString("Amount", arialRegularFont, whiteBrush, headerAmountBounds,
                                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            graphics.DrawString("$" + products.amount_paid.ToString(), arialBoldFont, whiteBrush,
                                new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
                                PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));



            PdfTextElement textElement = new PdfTextElement("Invoice Number: " + products.id.ToString(), arialRegularFont);

            PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120));

            textElement.Text = "Date : " + DateTime.Now.ToString("dddd dd, MMMM yyyy");
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace));
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db");
            var db     = new SQLiteConnection(dbpath);
            if (products.client_id != null)
            {
                var client = (db.Table <Client>().ToList().Where(clien => clien.id == int.Parse(products.client_id)).FirstOrDefault());
                textElement.Text = "Bill To:";
                layoutResult     = textElement.Draw(page, new PointF(margin, 120));

                textElement.Text = client.enname;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.address;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.email;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.phone;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            }

            #endregion

            #region Invoice data
            PdfGrid        grid            = new PdfGrid();
            DataTable      dataTable       = new DataTable("EmpDetails");
            List <Product> customerDetails = new List <Product>();
            //Add columns to the DataTable
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Price");
            dataTable.Columns.Add("Qty");
            dataTable.Columns.Add("Disc");
            dataTable.Columns.Add("Total");

            //Add rows to the DataTable.
            foreach (var item in products.products)
            {
                Product customer = new Product();
                customer.id          = products.products.IndexOf(item) + 1;
                customer.Enname      = item.Enname;
                customer.sale_price  = item.sale_price;
                customer.quantity    = item.quantity;
                customer.discount    = item.discount;
                customer.total_price = item.total_price;
                customerDetails.Add(customer);
                dataTable.Rows.Add(new string[] { customer.id.ToString(), customer.Enname, customer.sale_price.ToString(),
                                                  customer.quantity.ToString(), customer.discount.ToString(), customer.total_price.ToString() });
            }

            //Assign data source.
            grid.DataSource = dataTable;


            grid.Columns[1].Width      = 150;
            grid.Style.Font            = arialRegularFont;
            grid.Style.CellPadding.All = 5;

            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable1Light);

            layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40));

            textElement.Text = "Grand Total: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom +
                                                                 lineSpace));

            float totalAmount = float.Parse(products.total_price);
            textElement.Text = "$" + totalAmount.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            //graphics.DrawString("$" + totalAmount.ToString(), arialBoldFont, whiteBrush,
            //    new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
            //    PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            textElement.Text = "Total Discount: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom +
                                                                 lineSpace));

            float totalDisc = float.Parse(products.discount);
            textElement.Text = "$" + totalDisc.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            //graphics.DrawString("$" + totalDisc.ToString(), arialBoldFont, whiteBrush,
            //    new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
            //    PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));


            #endregion

            #region Seller information
            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0));
            layoutResult = line.Draw(page, new PointF(0, pageHeight - 100));

            textElement.Text = "IttezanPos";
            textElement.Font = arialRegularFont;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3)));
            textElement.Text = "Buradah,  AlQassim, Saudi Arabia";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Any Questions? ittezan.com";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            #endregion

            //#region Create ZUGFeRD XML

            ////Create //ZUGFeRD Invoice
            //ZugferdInvoice invoice = new ZugferdInvoice("2058557939", DateTime.Now, CurrencyCodes.USD);

            ////Set ZUGFeRD profile to basic
            //invoice.Profile = ZugferdProfile.Basic;

            ////Add buyer details
            //invoice.Buyer = new UserDetails
            //{
            //    ID = "Abraham_12",
            //    Name = "Abraham Swearegin",
            //    ContactName = "Swearegin",
            //    City = "United States, California",
            //    Postcode = "9920",
            //    Country = CountryCodes.US,
            //    Street = "9920 BridgePointe Parkway"
            //};

            ////Add seller details
            //invoice.Seller = new UserDetails
            //{
            //    ID = "Adventure_123",
            //    Name = "AdventureWorks",
            //    ContactName = "Adventure support",
            //    City = "Austin,TX",
            //    Postcode = "78721",
            //    Country = CountryCodes.US,
            //    Street = "800 Interchange Blvd"
            //};


            //IEnumerable<Product> products = saleproducts;

            //foreach (Product product in products)
            //    invoice.AddProduct(product);


            //invoice.TotalAmount = totalAmount;

            //MemoryStream zugferdXML = new MemoryStream();
            //invoice.Save(zugferdXML);
            //#endregion

            #region Embed ZUGFeRD XML to PDF

            //Attach ZUGFeRD XML to PDF
            //PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXML);
            //attachment.Relationship = PdfAttachmentRelationship.Alternative;
            //attachment.ModificationDate = DateTime.Now;
            //attachment.Description = "ZUGFeRD-invoice";
            //attachment.MimeType = "application/xml";
            //document.Attachments.Add(attachment);
            #endregion
            //Creates an attachment
            MemoryStream stream = new MemoryStream();
            //    Stream invoiceStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.Data.ZUGFeRD-invoice.xml");

            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", stream);

            attachment.Relationship = PdfAttachmentRelationship.Alternative;

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "ZUGFeRD-invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);

            //Save the document into memory stream



            document.Save(stream);

            //Close the document

            document.Close(true);
            DependencyService.Get <IPrintService>().Print(stream, "تقرير العملاء.pdf");
            //    await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("تقرير العملاء.pdf", "application/pdf", stream);
        }
Exemple #51
0
 protected internal PdfCatalog(PdfDocument pdfDocument)
     : this((PdfDictionary) new PdfDictionary().MakeIndirect(pdfDocument))
 {
 }
Exemple #52
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Books books = new Books();

            PdfDocument document = new PdfDocument(); // Create a new PDF document

            document.Info.Title  = "Created with PDFsharp";
            document.Info.Author = "Faktury2020";
            PdfPage         page    = document.AddPage();                           // Create an empty page
            XGraphics       gfx     = XGraphics.FromPdfPage(page);                  // Get an XGraphics object for drawing
            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode); // Set font encoding to unicode
            //albo mogę ew. spróbować jeśli przestanie działać:
            //gfx.MUH = PdfFontEncoding.Unicode;
            //gfx.MFEH = PdfFontEmbedding.Default;
            XFont font = new XFont("Times New Roman", 12, XFontStyle.Regular, options); //Then you'll create a font:



            Document doc = new Document(); //tu startuje migradoc, po kolei: dokument, sekcja i paragraf..
            Section  sec = doc.AddSection();

            //def tableMiejsceiDataWystawienia TUTAJ
            Table tableMiejsceiDataWystawienia = new Table();

            tableMiejsceiDataWystawienia.Borders.Width = 0.0;

            Column columnMiejsceiDataWystawienia = tableMiejsceiDataWystawienia.AddColumn(Unit.FromCentimeter(5));

            columnMiejsceiDataWystawienia.Format.Alignment = ParagraphAlignment.Left;
            Column columnMiejsceiDataWystawienia2 = tableMiejsceiDataWystawienia.AddColumn(Unit.FromCentimeter(12));

            columnMiejsceiDataWystawienia2.Format.Alignment = ParagraphAlignment.Right;


            Row  rowMiejsceiDataWystawienia  = tableMiejsceiDataWystawienia.AddRow();
            Cell cellMiejsceiDataWystawienia = rowMiejsceiDataWystawienia.Cells[0];

            cellMiejsceiDataWystawienia = rowMiejsceiDataWystawienia.Cells[0];
            cellMiejsceiDataWystawienia.AddParagraph("Katowice");
            // rowKontoBankowe.Format.Alignment = ParagraphAlignment.Right;


            cellMiejsceiDataWystawienia = rowMiejsceiDataWystawienia.Cells[1];
            cellMiejsceiDataWystawienia.AddParagraph("Wystawiono dnia: 16-03-2020");

            doc.LastSection.Add(tableMiejsceiDataWystawienia);

            //Paragraph miasto = sec.AddParagraph();
            //miasto.AddText("Katowice");
            //miasto.Format.Alignment = ParagraphAlignment.Left;

            //Paragraph dataWystawienia = sec.AddParagraph();
            //dataWystawienia.AddText("Wystawiono dnia: 16-03-2020");
            //dataWystawienia.Format.Alignment = ParagraphAlignment.Right;

            sec.AddParagraph();

            Paragraph numerFaktury = sec.AddParagraph();

            numerFaktury.AddText("Faktura proforma 1-TEST-2-2020");
            numerFaktury.Format.Font.Bold = true;
            numerFaktury.Format.Alignment = ParagraphAlignment.Center;

            sec.AddParagraph();

            Paragraph dataSprzedazy = sec.AddParagraph();

            dataSprzedazy.AddText("Data sprzedaży: 2-2020");
            dataSprzedazy.Format.Font.Bold = true;
            dataSprzedazy.Format.Alignment = ParagraphAlignment.Right;

            Paragraph sposobZaplaty = sec.AddParagraph();

            sposobZaplaty.AddText("Forma płatności: GOTÓWKA");
            sposobZaplaty.Format.Font.Bold = true;
            sposobZaplaty.Format.Alignment = ParagraphAlignment.Right;

            Paragraph terminPlatnosci = sec.AddParagraph();

            terminPlatnosci.AddText("Termin płatności: 01-04-2020");
            terminPlatnosci.Format.Font.Bold = true;
            terminPlatnosci.Format.Alignment = ParagraphAlignment.Right;

            //def table sprzedawca-nabywca(SN) and its parts
            Table tableSN = new Table();

            tableSN.Borders.Width = 0.0;
            Column columnSN = tableSN.AddColumn(Unit.FromCentimeter(9));

            columnSN.Format.Alignment = ParagraphAlignment.Left;
            _ = tableSN.AddColumn(Unit.FromCentimeter(9));
            columnSN.Format.Alignment = ParagraphAlignment.Left;
            Row  rowSN  = tableSN.AddRow();
            Cell cellSN = rowSN.Cells[0];

            cellSN = rowSN.Cells[0];
            cellSN.AddParagraph("Sprzedawca");
            cellSN.Format.Font.Bold = true;
            cellSN = rowSN.Cells[1];
            cellSN.AddParagraph("Nabywca");
            cellSN.Format.Font.Bold = true;

            Row  rowEmpty  = tableSN.AddRow();
            Cell cellEmpty = rowEmpty.Cells[0];

            cellEmpty = rowEmpty.Cells[0];
            // cellEmpty.AddParagraph(""); //to jest niepotrzebne = i tak jest pusta linia
            cellEmpty = rowEmpty.Cells[1];
            // cellEmpty.AddParagraph(""); //to jest niepotrzebne = i tak jest pusta linia

            Row  rowNazwaSprzedawcyiNabywcy  = tableSN.AddRow();
            Cell cellNazwaSprzedawcyiNabywcy = rowEmpty.Cells[0];

            cellNazwaSprzedawcyiNabywcy = rowNazwaSprzedawcyiNabywcy.Cells[0];
            cellNazwaSprzedawcyiNabywcy.AddParagraph("xSolutions Sp. z o.o.");
            cellNazwaSprzedawcyiNabywcy.Format.Font.Bold = true;
            cellNazwaSprzedawcyiNabywcy = rowNazwaSprzedawcyiNabywcy.Cells[1];
            cellNazwaSprzedawcyiNabywcy.AddParagraph("Aldona Nieznana");
            cellNazwaSprzedawcyiNabywcy.Format.Font.Bold = true;

            Row  rowUlicaSprzedawcyiNabywcy  = tableSN.AddRow();
            Cell cellUlicaSprzedawcyiNabywcy = rowEmpty.Cells[0];

            cellUlicaSprzedawcyiNabywcy = rowUlicaSprzedawcyiNabywcy.Cells[0];
            cellUlicaSprzedawcyiNabywcy.AddParagraph("ul. Mickiewicza 29");
            cellUlicaSprzedawcyiNabywcy = rowUlicaSprzedawcyiNabywcy.Cells[1];
            cellUlicaSprzedawcyiNabywcy.AddParagraph("ul Nieznana 20");

            Row  rowMiastoiKodSprzedawcyiNabywcy  = tableSN.AddRow();
            Cell cellMiastoiKodSprzedawcyiNabywcy = rowEmpty.Cells[0];

            cellMiastoiKodSprzedawcyiNabywcy = rowUlicaSprzedawcyiNabywcy.Cells[0];
            cellMiastoiKodSprzedawcyiNabywcy.AddParagraph("40-085 Katowice");
            cellMiastoiKodSprzedawcyiNabywcy = rowUlicaSprzedawcyiNabywcy.Cells[1];
            cellMiastoiKodSprzedawcyiNabywcy.AddParagraph("41-200 Sosnowiec");

            Row rowEmpty2 = tableSN.AddRow();
            // Cell cellEmpty2 = rowEmpty2.Cells[0];
            //cellEmpty2 = rowEmpty2.Cells[0];

            //cellEmpty2 = rowEmpty2.Cells[1];


            Row  rowNIPSprzedawcyiNabywcy  = tableSN.AddRow();
            Cell cellNIPSprzedawcyiNabywcy = rowEmpty.Cells[0];

            cellNIPSprzedawcyiNabywcy = rowNIPSprzedawcyiNabywcy.Cells[0];
            cellNIPSprzedawcyiNabywcy.AddParagraph("NIP 634-293-59-61");
            cellNIPSprzedawcyiNabywcy.Format.Font.Bold = true;
            cellNIPSprzedawcyiNabywcy = rowNIPSprzedawcyiNabywcy.Cells[1];
            cellNIPSprzedawcyiNabywcy.AddParagraph("NIP 000-000-00-00");
            cellNIPSprzedawcyiNabywcy.Format.Font.Bold = true;

            Row rowEmpty3 = tableSN.AddRow();

            //def table bank i konto bankowe
            Table tableBankiKontoBankowe = new Table();

            tableBankiKontoBankowe.Borders.Width = 0.0;
            Column columnBankiKontoBankowe1 = tableBankiKontoBankowe.AddColumn(Unit.FromCentimeter(5));

            columnBankiKontoBankowe1.Format.Alignment = ParagraphAlignment.Right;
            Column columnBankiKontoBankowe2 = tableBankiKontoBankowe.AddColumn(Unit.FromCentimeter(9));

            columnBankiKontoBankowe2.Format.Alignment = ParagraphAlignment.Left;
            Row  rowBankiKontoBankowe  = tableBankiKontoBankowe.AddRow();
            Cell cellBankiKontoBankowe = rowBankiKontoBankowe.Cells[0];

            cellBankiKontoBankowe = rowBankiKontoBankowe.Cells[0];
            cellBankiKontoBankowe.AddParagraph("Bank: ");
            cellBankiKontoBankowe.Format.Font.Bold = true;
            cellBankiKontoBankowe = rowBankiKontoBankowe.Cells[1];
            cellBankiKontoBankowe.AddParagraph("Nest Bank");
            cellBankiKontoBankowe.Format.Font.Bold = true;

            //def konto bankowe
            Row  rowKontoBankowe  = tableBankiKontoBankowe.AddRow();
            Cell cellKontoBankowe = rowKontoBankowe.Cells[0];

            cellKontoBankowe = rowKontoBankowe.Cells[0];
            cellKontoBankowe.AddParagraph("Konto: ");
            // rowKontoBankowe.Format.Alignment = ParagraphAlignment.Right;
            cellKontoBankowe.Format.Font.Bold = true;

            cellKontoBankowe = rowKontoBankowe.Cells[1];
            cellKontoBankowe.AddParagraph("44 2530 0008 2064 1044 1937 0001");
            cellKontoBankowe.Format.Font.Bold = true;

            Row rowEmpty4 = tableBankiKontoBankowe.AddRow();

            // chcę, aby 'POZYCJE FAKTURY' było napisane nie w obramowaniu a nad tabelą, robię więc manewr polegający na przedłużeniu niewidocznej tabeli
            Row  rowPozycjeFaktury  = tableBankiKontoBankowe.AddRow();
            Cell cellPozycjeFaktury = rowPozycjeFaktury.Cells[1];

            cellPozycjeFaktury = rowPozycjeFaktury.Cells[1];
            cellPozycjeFaktury.AddParagraph("POZYCJE FAKTURY");
            cellPozycjeFaktury.Format.Font.Bold = true;
            rowPozycjeFaktury.Format.Alignment  = ParagraphAlignment.Left;


            doc.LastSection.Add(tableSN);
            doc.LastSection.Add(tableBankiKontoBankowe);

            //def table Pozycje-Faktury(PF)
            Table table = new Table();

            table.Borders.Width = 0.5;

            //def column Lp
            Column column = table.AddColumn(Unit.FromCentimeter(1));


            //def colum NazwaTowaruLubUsługi
            _ = table.AddColumn(Unit.FromCentimeter(6));
            // def column Ilość
            _ = table.AddColumn(Unit.FromCentimeter(1));
            // def column Jednostka
            _ = table.AddColumn(Unit.FromCentimeter(1.5));
            // def column Wartość jednostkowa brutto
            _ = table.AddColumn(Unit.FromCentimeter(4));
            // def column Wartość brutto
            _ = table.AddColumn(Unit.FromCentimeter(3));

            //def header of table
            Row row = table.AddRow();

            Cell cell0 = row.Cells[0];

            cell0.AddParagraph("Lp.");
            cell0.Format.Font.Bold = true;
            cell0.Format.Alignment = ParagraphAlignment.Center;

            Cell cell1 = row.Cells[1];

            cell1.AddParagraph("Nazwa towaru lub usługi");
            cell1.Format.Font.Bold = true;
            cell1.Format.Alignment = ParagraphAlignment.Center;

            Cell cell2 = row.Cells[2];

            cell2.AddParagraph("Ilość");
            cell2.Format.Font.Bold = true;
            cell2.Format.Alignment = ParagraphAlignment.Center;

            Cell cell3 = row.Cells[3];

            cell3.AddParagraph("Jedn.");
            cell3.Format.Font.Bold = true;
            cell3.Format.Alignment = ParagraphAlignment.Center;

            Cell cell4 = row.Cells[4];

            cell4.AddParagraph("Wartość jednostkowa brutto PLN");
            cell4.Format.Font.Bold = true;
            cell4.Format.Alignment = ParagraphAlignment.Center;

            Cell cell5 = row.Cells[5];

            cell5.AddParagraph("Wartość brutto \n PLN");
            cell5.Format.Font.Bold = true;
            cell5.Format.Alignment = ParagraphAlignment.Center;

            Row  row2     = table.AddRow();
            Cell cellR2C0 = row2.Cells[0];

            cellR2C0.AddParagraph("1");
            cellR2C0.Format.Alignment = ParagraphAlignment.Center;

            Cell cellR2C1 = row2.Cells[1];

            cellR2C1.AddParagraph("Abonament xBiuro - pakiet STANDARD na 12-MIESIĘCY");
            cellR2C1.Format.Alignment = ParagraphAlignment.Center;

            Cell cellR2C2 = row2.Cells[2];

            cellR2C2.AddParagraph("1");
            cellR2C2.Format.Alignment = ParagraphAlignment.Center;

            Cell cellR2C3 = row2.Cells[3];

            cellR2C3.AddParagraph("usługa");
            cellR2C3.Format.Alignment = ParagraphAlignment.Center;

            Cell cellR2C4 = row2.Cells[4];

            cellR2C4.AddParagraph("723,24");
            cellR2C4.Format.Alignment = ParagraphAlignment.Center;

            Cell cellR2C5 = row2.Cells[5];

            cellR2C5.AddParagraph("723,24");
            cellR2C5.Format.Alignment = ParagraphAlignment.Center;



            //foreach (var elem in books)
            //{
            //    row = table.AddRow();

            //    cell = row.Cells[0];
            //    cell.AddParagraph(elem.author);

            //    cell = row.Cells[1];
            //    cell.AddParagraph(elem.title);

            //    cell = row.Cells[2];
            //    cell.AddParagraph(elem.year.ToString());

            //}

            //add table to document
            doc.LastSection.Add(table);

            Paragraph slownie = sec.AddParagraph();

            slownie.Format.Font.Bold = true;
            slownie.AddText("\n SŁOWNIE: SIEDEMSET DWADZIEŚCIA TRZY ZŁOTE I 24/100 GROSZY BRUTTO");

            //def tablePODSUMOWANIE Razem, Zapłacono, Pozostało do zapłaty
            Table tablePodsumowanie = new Table();

            tablePodsumowanie.Borders.Width = 0.5;
            Column columnPodsumowanie1 = tablePodsumowanie.AddColumn(Unit.FromCentimeter(8.25));

            columnPodsumowanie1.Format.Alignment = ParagraphAlignment.Right;
            Column columnPodsumowanie2 = tablePodsumowanie.AddColumn(Unit.FromCentimeter(8.25));

            columnPodsumowanie2.Format.Alignment = ParagraphAlignment.Center;
            Row  rowPodsumowanie1  = tablePodsumowanie.AddRow();
            Cell cellPodsumowanie1 = rowPodsumowanie1.Cells[0];

            cellPodsumowanie1 = rowPodsumowanie1.Cells[0];
            cellPodsumowanie1.AddParagraph("Razem");
            cellPodsumowanie1.Format.Font.Bold = true;
            cellPodsumowanie1 = rowPodsumowanie1.Cells[1];
            cellPodsumowanie1.AddParagraph("723,24 PLN");
            cellPodsumowanie1.Format.Font.Bold = false;

            Row  rowPodsumowanie2  = tablePodsumowanie.AddRow();
            Cell cellPodsumowanie2 = rowPodsumowanie2.Cells[0];

            cellPodsumowanie2 = rowPodsumowanie2.Cells[0];
            cellPodsumowanie2.AddParagraph("Zapłacono");
            // rowKontoBankowe.Format.Alignment = ParagraphAlignment.Right;
            cellPodsumowanie2.Format.Font.Bold = true;

            cellPodsumowanie2 = rowPodsumowanie2.Cells[1];
            cellPodsumowanie2.AddParagraph("0,00 PLN");
            cellPodsumowanie2.Format.Font.Bold = false;

            Row  rowPodsumowanie3  = tablePodsumowanie.AddRow();
            Cell cellPodsumowanie3 = rowPodsumowanie3.Cells[0];

            cellPodsumowanie3 = rowPodsumowanie3.Cells[0];
            cellPodsumowanie3.AddParagraph("Pozostało do zaplaty");
            // rowKontoBankowe.Format.Alignment = ParagraphAlignment.Right;
            cellPodsumowanie3.Format.Font.Bold = true;

            cellPodsumowanie3 = rowPodsumowanie3.Cells[1];
            cellPodsumowanie3.AddParagraph("723,24 PLN");
            cellPodsumowanie3.Format.Font.Bold = false;

            doc.LastSection.Add(tablePodsumowanie);

            Paragraph uwagi = sec.AddParagraph();

            uwagi.Format.Font.Bold = false;
            uwagi.AddText("UWAGI: Zwolnienie podmiotowe z VAT wg. art. 113 ust. 1 Ustawy o VAT. W przypadku braku opłacenia faktury w terminie świadczenie usługi zostanie automatycznie wstrzymane. \n \n \n");


            //def table bank i konto bankowe
            Table tablePodpisy = new Table();

            tablePodpisy.Borders.Width = 0.0;
            Column columnPodpisy1 = tablePodpisy.AddColumn(Unit.FromCentimeter(8.25));

            columnPodpisy1.Format.Alignment = ParagraphAlignment.Center;
            Column columnPodpisy2 = tablePodpisy.AddColumn(Unit.FromCentimeter(8.25));

            columnPodpisy2.Format.Alignment = ParagraphAlignment.Center;
            Row  rowPodpisy  = tablePodpisy.AddRow();
            Cell cellPodpisy = rowPodpisy.Cells[0];

            cellPodpisy = rowPodpisy.Cells[0];
            cellPodpisy.AddParagraph("Faktura bez podpisu odbiorcy faktury ");
            cellPodpisy = rowPodpisy.Cells[1];
            cellPodpisy.AddParagraph("Osoba upoważniona do wystawienia faktury ");


            Row  rowPodpisy2  = tablePodpisy.AddRow();
            Cell cellPodpisy2 = rowPodpisy2.Cells[0];

            cellPodpisy2 = rowPodpisy.Cells[0];
            cellPodpisy2.AddParagraph(" ");

            cellPodpisy2 = rowPodpisy.Cells[1];
            cellPodpisy2.AddParagraph("\n \n Tomasz Chajduga");

            doc.LastSection.Add(tablePodpisy);


            // Create a renderer and prepare (=layout) the document
            MigraDoc.Rendering.DocumentRenderer docRenderer = new MigraDoc.Rendering.DocumentRenderer(doc);
            docRenderer.PrepareDocument();
            gfx.MUH = PdfFontEncoding.Unicode;

            docRenderer.RenderPage(gfx, 1);


            const string filename = "HelloWorld4.pdf"; //When drawing is done, write the file

            document.Save(filename);                   // Save the document...

            //Process.Start(filename); // ...and start a viewer.
        }
        private void ReportDate_OnClick(object sender, RoutedEventArgs e)
        {
            var date = new dates();

            date.ShowDialog();
            try
            {
                using (MsSqlContext db = new MsSqlContext())
                {
                    var places_list = db.places_list.Include(t => t.sessions).Include(g => g.User).Where(c => c.status == "Куплено").Where(x => x.date_of_operation >= dates.begin && x.date_of_operation <= dates.end).ToList();
                    var dest        = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Отчёт по продажам за промежуток времени.pdf";
                    var file        = new FileInfo(dest);
                    file.Directory.Create();
                    var pdf      = new PdfDocument(new PdfWriter(dest));
                    var document = new Document(pdf, PageSize.A2.Rotate());
                    var font     = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);

                    float[] columnWidths = { 10, 10, 10, 8 };
                    var     table        = new Table(UnitValue.CreatePercentArray(columnWidths));

                    var cell = new Cell(1, 4)
                               .Add(new Paragraph("Отчёт за промежуток времени"))
                               .SetFont(font)
                               .SetFontSize(13)
                               .SetFontColor(DeviceGray.WHITE)
                               .SetBackgroundColor(DeviceGray.BLACK)
                               .SetWidth(600)
                               .SetTextAlignment(TextAlignment.CENTER);
                    table.AddHeaderCell(cell);

                    Cell[] headerFooter =
                    {
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("С")),
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("По")),
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Количество купленных билетов")),
                        new Cell().SetFont(font).SetWidth(100).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Общая сумма"))
                    };

                    foreach (var hfCell in headerFooter)
                    {
                        table.AddHeaderCell(hfCell);
                    }

                    int   Count_of_places = places_list.Count;
                    float Summ_price      = 0;

                    for (int i = 0; i < places_list.Count; i++)
                    {
                        Summ_price = places_list[i].sessions.price_of_tickets + Summ_price;
                    }
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(dates.begin.ToString())));
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(dates.end.ToString())));
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(Count_of_places.ToString())));
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(Summ_price.ToString())));
                    document.Add(table);
                    document.Close();
                    var p = new Process
                    {
                        StartInfo = new ProcessStartInfo(dest)
                        {
                            UseShellExecute = true
                        }
                    };
                    p.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #54
0
        internal virtual PdfDestination CopyDestination(PdfObject dest, IDictionary <PdfPage, PdfPage> page2page, PdfDocument
                                                        toDocument)
        {
            PdfDestination d = null;

            if (dest.IsArray())
            {
                PdfObject pageObject = ((PdfArray)dest).Get(0);
                foreach (PdfPage oldPage in page2page.Keys)
                {
                    if (oldPage.GetPdfObject() == pageObject)
                    {
                        // in the copiedArray old page ref will be correctly replaced by the new page ref as this page is already copied
                        PdfArray copiedArray = (PdfArray)dest.CopyTo(toDocument, false);
                        d = new PdfExplicitDestination(copiedArray);
                        break;
                    }
                }
            }
            else
            {
                if (dest.IsString())
                {
                    PdfNameTree destsTree = GetNameTree(PdfName.Dests);
                    IDictionary <String, PdfObject> dests = destsTree.GetNames();
                    String   srcDestName  = ((PdfString)dest).ToUnicodeString();
                    PdfArray srcDestArray = (PdfArray)dests.Get(srcDestName);
                    if (srcDestArray != null)
                    {
                        PdfObject pageObject = srcDestArray.Get(0);
                        foreach (PdfPage oldPage in page2page.Keys)
                        {
                            if (oldPage.GetPdfObject() == pageObject)
                            {
                                d = new PdfStringDestination(srcDestName);
                                if (!IsEqualSameNameDestExist(page2page, toDocument, srcDestName, srcDestArray, oldPage))
                                {
                                    // in the copiedArray old page ref will be correctly replaced by the new page ref as this page is already copied
                                    PdfArray copiedArray = (PdfArray)srcDestArray.CopyTo(toDocument, false);
                                    toDocument.AddNamedDestination(srcDestName, copiedArray);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            return(d);
        }
        private PdfPageBase DrawPages(PdfDocument doc)
        {
            //margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins       margin   = new PdfMargins();

            margin.Top    = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left   = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right  = margin.Left;

            // Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            float y = 10;

            //title
            PdfBrush        brush1  = PdfBrushes.Black;
            PdfTrueTypeFont font1   = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);

            page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Part List", format1).Height;
            y = y + 5;

            //create data table
            PdfTable table = new PdfTable();

            table.Style.CellPadding = 2;
            table.Style.BorderPen   = new PdfPen(brush1, 0.75f);
            table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue;
            table.Style.DefaultStyle.Font            = new PdfTrueTypeFont(new Font("Arial", 10f));
            table.Style.AlternateStyle = new PdfCellStyle();
            table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow;
            table.Style.AlternateStyle.Font            = new PdfTrueTypeFont(new Font("Arial", 10f));
            table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
            table.Style.HeaderStyle.Font            = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
            table.Style.HeaderStyle.StringFormat    = new PdfStringFormat(PdfTextAlignment.Center);
            table.Style.ShowHeader = true;

            using (OleDbConnection conn = new OleDbConnection())
            {
                conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\Data\demo.mdb";
                OleDbCommand command = new OleDbCommand();
                command.CommandText
                    = " select Description, OnHand, OnOrder, Cost, ListPrice from parts ";
                command.Connection = conn;
                using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
                {
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);
                    table.DataSourceType = PdfTableDataSourceType.TableDirect;
                    table.DataSource     = dataTable;
                }
            }
            float width
                = page.Canvas.ClientSize.Width
                  - (table.Columns.Count + 1) * table.Style.BorderPen.Width;

            for (int i = 0; i < table.Columns.Count; i++)
            {
                if (i == 0)
                {
                    table.Columns[i].Width = width * 0.40f * width;
                    table.Columns[i].StringFormat
                        = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    table.Columns[i].Width = width * 0.15f * width;
                    table.Columns[i].StringFormat
                        = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }

            PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();

            tableLayout.Break  = PdfLayoutBreakType.FitElement;
            tableLayout.Layout = PdfLayoutType.Paginate;

            PdfLayoutResult result = table.Draw(page, new PointF(0, y), tableLayout);

            y = result.Bounds.Bottom + 3;

            PdfBrush        brush2 = PdfBrushes.Gray;
            PdfTrueTypeFont font2  = new PdfTrueTypeFont(new Font("Arial", 9f));

            result.Page.Canvas.DrawString(String.Format("* {0} parts in the list.", table.Rows.Count),
                                          font2, brush2, 5, y);

            return(result.Page);
        }
Exemple #56
0
        private void excelToPdfBtnClick(object sender, RoutedEventArgs e)
        {
            if (this.textBox1.Text != String.Empty && (string)this.textBox1.Tag != string.Empty)
            {
                if (File.Exists((string)this.textBox1.Tag))
                {
                    //Open the Excel Document to Convert
                    ExcelToPdfConverter converter = new ExcelToPdfConverter((string)this.textBox1.Tag);

                    //Intialize the PdfDocument
                    PdfDocument pdfDoc = new PdfDocument();

                    //Intialize the ExcelToPdfConverter Settings
                    ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings();

                    if ((bool)noScaleRadioBtn.IsChecked)
                    {
                        settings.LayoutOptions = LayoutOptions.NoScaling;
                    }
                    else if ((bool)allRowsRadioBtn.IsChecked)
                    {
                        settings.LayoutOptions = LayoutOptions.FitAllRowsOnOnePage;
                    }
                    else if ((bool)allColumnRadioBtn.IsChecked)
                    {
                        settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage;
                    }
                    else
                    {
                        settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage;
                    }

                    //Assign the PdfDocument to the templateDocument property of ExcelToPdfConverterSettings
                    settings.TemplateDocument = pdfDoc;
                    settings.DisplayGridLines = GridLinesDisplayStyle.Invisible;
                    //Convert Excel Document into PDF document
                    pdfDoc = converter.Convert(settings);

                    //Save the PDF file
                    pdfDoc.Save("ExceltoPdf.pdf");

                    //Message box confirmation to view the created document.
                    if (MessageBox.Show("Conversion Successful. Do you want to view the PDF File?", "Status", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(@"ExceltoPdf.pdf");
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                        }
                    }
                }

                else
                {
                    MessageBox.Show("File doesn’t exist");
                }
            }

            else
            {
                MessageBox.Show("Browse an Excel document to convert to Pdf", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
 public void LoadPDF(string source)
 {
     //webBrowserViewerPdf.Source = new Uri(source);
     (wfh.Child as PdfViewer).Document = PdfDocument.Load(source);
 }
Exemple #58
-1
        public PdfType0Font(PdfDocument document, XFont font, bool vertical)
            : base(document)
        {
            Elements.SetName(Keys.Type, "/Font");
            Elements.SetName(Keys.Subtype, "/Type0");
            Elements.SetName(Keys.Encoding, vertical ? "/Identity-V" : "/Identity-H");

            OpenTypeDescriptor ttDescriptor = (OpenTypeDescriptor)FontDescriptorCache.GetOrCreateDescriptorFor(font);
            FontDescriptor = new PdfFontDescriptor(document, ttDescriptor);
            _fontOptions = font.PdfOptions;
            Debug.Assert(_fontOptions != null);

            _cmapInfo = new CMapInfo(ttDescriptor);
            _descendantFont = new PdfCIDFont(document, FontDescriptor, font);
            _descendantFont.CMapInfo = _cmapInfo;

            // Create ToUnicode map
            _toUnicode = new PdfToUnicodeMap(document, _cmapInfo);
            document.Internals.AddObject(_toUnicode);
            Elements.Add(Keys.ToUnicode, _toUnicode);

            BaseFont = font.GlyphTypeface.GetBaseName();
            // CID fonts are always embedded
            BaseFont = PdfFont.CreateEmbeddedFontSubsetName(BaseFont);

            FontDescriptor.FontName = BaseFont;
            _descendantFont.BaseFont = BaseFont;

            PdfArray descendantFonts = new PdfArray(document);
            Owner._irefTable.Add(_descendantFont);
            descendantFonts.Elements.Add(_descendantFont.Reference);
            Elements[Keys.DescendantFonts] = descendantFonts;
        }
    /// <summary>
    /// Initializes a new instance of the <see cref="PdfExtGState"/> class.
    /// </summary>
    /// <param name="document">The document.</param>
    public PdfExtGState(PdfDocument document)
      : base(document)
    {
      Elements.SetName(Keys.Type, "/ExtGState");

#if true_
  //AIS false
  //BM /Normal
  //ca 1
  //CA 1
  //op false
  //OP false
  //OPM 1
  //SA true
  //SMask /None
  //Type /ExtGState

      Elements.SetValue(Keys.AIS, new PdfBoolean(false)); // The alpha source
      Elements.SetName("/BM", "Normal");
      Elements.SetValue(Keys.op, new PdfBoolean(false));
      Elements.SetValue(Keys.OP, new PdfBoolean(false));
      Elements.SetValue(Keys.OPM, new PdfInteger(1));
      Elements.SetValue("/SA", new PdfBoolean(true));
      Elements.SetName("/SMask", "None");
#endif
    }
Exemple #60
-2
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("sample.pdf");

            //Use the default printer to print all the pages
            //doc.PrintDocument.Print();

            //Set the printer and select the pages you want to print

            PrintDialog dialogPrint = new PrintDialog();
            dialogPrint.AllowPrintToFile = true;
            dialogPrint.AllowSomePages = true;
            dialogPrint.PrinterSettings.MinimumPage = 1;
            dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
            dialogPrint.PrinterSettings.FromPage = 1;
            dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;

            if (dialogPrint.ShowDialog() == DialogResult.OK)
            {
                //Set the pagenumber which you choose as the start page to print
                doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
                //Set the pagenumber which you choose as the final page to print
                doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
                //Set the name of the printer which is to print the PDF
                doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;

                PrintDocument printDoc = doc.PrintDocument;
                dialogPrint.Document = printDoc;
                printDoc.Print();
            }
        }