Exemple #1
9
    static void Main(string[] args)
    {
      // Create a new PDF document
      PdfDocument document = new PdfDocument();

      // Create an empty page
      PdfPage page = document.AddPage();
      //page.Contents.CreateSingleContent().Stream.UnfilteredValue;

      // Get an XGraphics object for drawing
      XGraphics gfx = XGraphics.FromPdfPage(page);

      XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

      // Create a font
      XFont font = new XFont("Arial", 20, XFontStyle.Bold, options);

      // Draw the text
      gfx.DrawString("Hello, World!", font, XBrushes.Black,
        new XRect(0, 0, page.Width, page.Height),
        XStringFormats.Center);

      // Save the document...
      string filename = "HelloWorld.pdf";
      document.Save(filename);
      // ...and start a viewer.
      Process.Start(filename);
    }
Exemple #2
4
    static void Main(string[] args)
    {
      // Get a fresh copy of the sample PDF file
      string filename = "Portable Document Format.pdf";
      File.Copy(Path.Combine("../../../../../PDFs/", filename), 
        Path.Combine(Directory.GetCurrentDirectory(), filename), true);

      // Open the file
      PdfDocument inputDocument = PdfReader.Open(filename, PdfDocumentOpenMode.Import);

      string name = Path.GetFileNameWithoutExtension(filename);
      for (int idx = 0; idx < inputDocument.PageCount; idx++)
      {
        // Create new document
        PdfDocument outputDocument = new PdfDocument();
        outputDocument.Version = inputDocument.Version;
        outputDocument.Info.Title =
          String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
        outputDocument.Info.Creator = inputDocument.Info.Creator;

        // Add the page and save it
        outputDocument.AddPage(inputDocument.Pages[idx]);
        outputDocument.Save(String.Format("{0} - Page {1}.pdf", name, idx + 1));
      }
    }
        public static bool Genereer(Deelnemer deelnemer, DeelnemerVerhuisd deelnemerVerhuisd)
        {
            _deelnemer = deelnemer;
            _event = deelnemerVerhuisd;

            // start pdf document
            _document = new PdfDocument();
            _document.Info.Title = "Verhuisbrief " + _deelnemer.Naam;
            _document.Info.Author = "Verhuisbrief Generator";

            // voeg pagina toe
            _page = _document.AddPage();
            _gfx = XGraphics.FromPdfPage(_page);

            // vul pagina
            PlaatsLogo();
            PlaatsTitel();
            PlaatsNAWGegevens();
            PlaatsInhoud();

            // sla document op
            SlaPdfOp();

            return true;
        }
Exemple #4
1
        public PdfDocument Merge( string[] filePaths, Action afterEachAddedFileAction )
        {
            PdfDocument mergedDocument = new PdfDocument();

            foreach ( var filePath in filePaths )
            {
                try
                {
                    using ( PdfDocument documentToAdd = _pdfReader.ReadFile( filePath ) )
                    {
                        for ( int i = 0; i < documentToAdd.PageCount; i++ )
                        {
                            PdfPage page = documentToAdd.Pages[ i ];

                            mergedDocument.AddPage( page );
                        }
                    }
                }
                catch ( Exception ex )
                {
                    string errorMessage = string.Format( "An error occurred processing the following file: {0}\n\nError Message: {1}\n\nFull Error: {2}", filePath, ex.Message, ex );

                    MessageBox.Show( errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error );
                }

                if ( afterEachAddedFileAction != null )
                {
                    afterEachAddedFileAction();
                }
            }

            return mergedDocument;
        }
Exemple #5
0
 internal PdfPage CreatePage(PdfDocument doc, FixedPage fixedPage)
 {
   PdfPage page = doc.Pages.Add();
   page.Width = XUnit.FromPresentation(fixedPage.Width);
   page.Height = XUnit.FromPresentation(fixedPage.Height);
   return page;
 }
        private string SaveDocument(Document document)
        {
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);

            pdfRenderer.Document = document;
            pdfRenderer.RenderDocument();
            PdfSharp.Pdf.PdfDocument pdfdoc = pdfRenderer.PdfDocument;
            pdfdoc.ViewerPreferences.FitWindow = false;
            pdfdoc.PageLayout = PdfSharp.Pdf.PdfPageLayout.SinglePage;
            pdfdoc.PageMode   = PdfSharp.Pdf.PdfPageMode.UseNone;
            //pdfdoc.Info.Keywords = "HORIZON HOTEL & VILLAS, AGHIOS IOANN, AirportCode:  JMK,  37.418820 ,25.314735  , latitude: 37.418820 , longitude: 25.314735";
            //pdfdoc.Info.Subject = "HORIZON HOTEL & VILLAS, AGHIOS IOANN, AirportCode:  JMK,  37.418820 ,25.314735  , latitude: 37.418820 , longitude: 25.314735";
            //pdfdoc.Info.Title = "HORIZON HOTEL & VILLAS, AGHIOS IOANN, AirportCode:  JMK,  37.418820 ,25.314735  , latitude: 37.418820 , longitude: 25.314735";

            //pdfdoc.Info.Creator = "HORIZON HOTEL & VILLAS, AGHIOS IOANN, AirportCode:  JMK,  37.418820 ,25.314735  , latitude: 37.418820 , longitude: 25.314735";
            //pdfdoc.Info.Author = "HORIZON HOTEL & VILLAS, AGHIOS IOANN, AirportCode:  JMK,  37.418820 ,25.314735  , latitude: 37.418820 , longitude: 25.314735";

            if (!System.IO.Directory.Exists(travelDocumentFolder))
            {
                System.IO.Directory.CreateDirectory(travelDocumentFolder);
            }

            string fileName = travelDocumentFolder + "\\Certificate.pdf";

            pdfRenderer.PdfDocument.Save(fileName);

            System.Diagnostics.Process.Start(fileName);

            return(fileName);
        }
Exemple #7
0
        public ImportedImage ImportImage(StreamReaderHelper stream, PdfDocument document)
        {
            try
            {
                stream.CurrentOffset = 0;
                int offsetImageData;
                if (TestBitmapFileHeader(stream, out offsetImageData))
                {
                    // Magic: TestBitmapFileHeader updates stream.CurrentOffset on success.

                    ImagePrivateDataBitmap ipd = new ImagePrivateDataBitmap(stream.Data, stream.Length);
                    ImportedImage ii = new ImportedImageBitmap(this, ipd, document);
                    if (TestBitmapInfoHeader(stream, ii, offsetImageData))
                    {
                        //stream.CurrentOffset = offsetImageData;
                        return ii;
                    }
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
            }
            return null;
        }
Exemple #8
0
    static void Main()
    {
      // 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 #9
0
        static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                DirectoryInfo directory = new DirectoryInfo(arg);

                string SavePath = string.Format("{0}.pdf",directory.Name);

                var files = directory.GetFiles("*.bmp");

                using (PdfDocument Document = new PdfDocument())
                {
                    foreach (var file in files)
                    {
                        var filename = file.FullName;
                        Console.WriteLine(filename);
                        PdfPage page = Document.AddPage();
                        using (XImage image = XImage.FromFile(filename))
                        {

                            page.Width = image.PointWidth;
                            page.Height = image.PointHeight;
                            using (XGraphics gfx = XGraphics.FromPdfPage(page))
                            {
                                gfx.DrawImage(image, 0, 0);
                            }
                        }
                    }
                    Document.Save(SavePath);
                }
            }
        }
        public void RenderPDF(string FileName)
        {
            PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument();

            // this.EnableSuccessiveRendering = true;

            doc.Info.Title    = Tablature.Title;
            doc.Info.Author   = Tablature.Artist;
            doc.Info.Subject  = Tablature.Album;
            doc.Info.Keywords = Tablature.Comments;
            foreach (Part p in score.Parts.Values)
            {
                SelectedPartID = p.ID;

                if (doc.Pages.Count > 0)
                {
                    PdfOutline outline = new PdfOutline(p.PartName, doc.Pages[doc.Pages.Count - 1], true);
                    doc.Outlines.Add(outline);
                }
                Render(doc, 600);
            }

            // Save the document...
            doc.Save(FileName);
        }
    void Page_Load(object sender, EventArgs e)
    {
      // Create new PDF document
      PdfDocument document = new PdfDocument();
      this.time = document.Info.CreationDate;
      document.Info.Title = "PDFsharp Clock Demo";
      document.Info.Author = "Stefan Lange";
      document.Info.Subject = "Server time: " +
        this.time.ToString("F", CultureInfo.InvariantCulture);

      // Create new page
      PdfPage page = document.AddPage();
      page.Width = XUnit.FromMillimeter(200);
      page.Height = XUnit.FromMillimeter(200);

      // Create graphics object and draw clock
      XGraphics gfx = XGraphics.FromPdfPage(page);
      RenderClock(gfx);

      // Send PDF to browser
      MemoryStream stream = new MemoryStream();
      document.Save(stream, false);
      Response.Clear();
      Response.ContentType = "application/pdf";
      Response.AddHeader("content-length", stream.Length.ToString());
      Response.BinaryWrite(stream.ToArray());
      Response.Flush();
      stream.Close();
      Response.End();
    }
Exemple #12
0
        public void Save (PdfDocument document)
        {
            // Save the document...  
            var filename = Path.Combine(ServerProperty.MapPath("~/Resources/PDF"), "test.pdf");
            document.Save(filename);

        }
Exemple #13
0
    static void Main()
    {
      // Create a new PDF document
      PdfDocument document = new PdfDocument();

      // Create a font
      XFont font = new XFont("Verdana", 16);

      // Create first page
      PdfPage page = document.AddPage();
      XGraphics gfx = XGraphics.FromPdfPage(page);
      gfx.DrawString("Page 1", font, XBrushes.Black, 20, 50, XStringFormats.Default);

      // Create the root bookmark. You can set the style and the color.
      PdfOutline outline = document.Outlines.Add("Root", page, true, PdfOutlineStyle.Bold, XColors.Red);

      // Create some more pages
      for (int idx = 2; idx <= 5; idx++)
      {
        page = document.AddPage();
        gfx = XGraphics.FromPdfPage(page);

        string text = "Page " + idx;
        gfx.DrawString(text, font, XBrushes.Black, 20, 50, XStringFormats.Default);

        // Create a sub bookmark
        outline.Outlines.Add(text, page, true);
      }

      // Save the document...
      const string filename = "Bookmarks_tempfile.pdf";
      document.Save(filename);
      // ...and start a viewer.
      Process.Start(filename);
    }
Exemple #14
0
        public static void PdfPrinter(FilterResults results)
        {
            PdfDocument pdf = new PdfDocument();
            int numPages;
            int reminder = 0;

            results.issues.OrderBy(i => i.fields.issuetype.name);
            List<JiraTicket> issues = new List<JiraTicket>();

                numPages = results.issues.Count / 6 + 1;
                reminder = results.issues.Count % 6;

                for (int i = 0; i < numPages - 1; i++)
                {
                    issues = results.issues.Skip(i*6).Take(6).ToList();
                    CreatePdfPage(issues, ref pdf);
                }

                if (reminder > 0)
                {
                    issues = results.issues.Skip((numPages-1)*6).Take(reminder).ToList();
                    CreatePdfPage(issues, ref pdf);
                }

            pdf.Save("C:/ProgramData/JiraCharts/issues.pdf");
        }
Exemple #15
0
        private static void CreatePdfPage(List<JiraTicket> issues, ref PdfDocument pdf)
        {
            PdfPage page = pdf.AddPage();
            page.Size = PdfSharp.PageSize.A4;
            page.Orientation = PdfSharp.PageOrientation.Landscape;

            for (int j = 0; j < issues.Count; j++)
            {
                string text = issues[j].fields.issuetype.name + System.Environment.NewLine + issues[j].key
                  + System.Environment.NewLine + issues[j].fields.summary + System.Environment.NewLine
                  + issues[j].fields.customfield_10008;

                XGraphics gfx = XGraphics.FromPdfPage(page);
                XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
                XTextFormatter tf = new XTextFormatter(gfx);
                XRect rect = new XRect();

                if (j < 3)
                {
                    rect = new XRect(15, 15 + j * 180, 400, 170);
                }
                else
                {
                    rect = new XRect(430, 15 + (j - 3) * 180, 400, 170);
                }

                gfx.DrawRectangle(XBrushes.SeaShell, rect);
                tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft);
                gfx.Dispose();
            }
        }
Exemple #16
0
        public static byte[] AppendImageToPdf(byte[] pdf, byte[] img, Point position, double scale)
        {
            using (System.IO.MemoryStream msPdf = new System.IO.MemoryStream(pdf))
            {
                using (System.IO.MemoryStream msImg = new System.IO.MemoryStream(img))
                {
                    System.Drawing.Image       image    = System.Drawing.Image.FromStream(msImg);
                    PdfSharp.Pdf.PdfDocument   document = PdfSharp.Pdf.IO.PdfReader.Open(msPdf);
                    PdfSharp.Pdf.PdfPage       page     = document.Pages[0];
                    PdfSharp.Drawing.XGraphics gfx      = PdfSharp.Drawing.XGraphics.FromPdfPage(page);
                    PdfSharp.Drawing.XImage    ximg     = PdfSharp.Drawing.XImage.FromGdiPlusImage(image);

                    gfx.DrawImage(
                        ximg,
                        position.X,
                        position.Y,
                        ximg.Width * scale,
                        ximg.Height * scale
                        );

                    using (System.IO.MemoryStream msFinal = new System.IO.MemoryStream())
                    {
                        document.Save(msFinal);
                        return(msFinal.ToArray());
                    }
                }
            }
        }
Exemple #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PdfPage"/> class.
 /// </summary>
 /// <param name="document">The document.</param>
 public PdfPage(PdfDocument document)
     : base(document)
 {
     Elements.SetName(Keys.Type, "/Page");
     Elements[Keys.Parent] = document.Pages.Reference;
     Initialize();
 }
 public Export_to_Pdf()
 {
     InitializeComponent();
     //Create object for pdf.
     document = new PdfDocument();
     page = document.AddPage();
     gfx = XGraphics.FromPdfPage(page);
     //Set by default values.
     font = new XFont("Arial", 12, XFontStyle.Regular);
     header_font = new XFont("Arial", 12, XFontStyle.Regular);
     page.Size = PageSize.A4;
     page.Orientation = PageOrientation.Portrait;
     //////////////////////////////////////////////////////////////////////
     //Create a fake questionanire to test the print process to pdf.
     if (questionaire != null)
     {
         List<Question> question_list = new List<Question>();
         List<Answer> answer_list = new List<Answer>();
         Answer ans = new Answer();
         ans.Answer_descr = "einai to dsfgdsfgsd";
         answer_list.Add(ans);
         answer_list.Add(ans);
         answer_list.Add(ans);
         Question quest = new Question() { AnswerList = answer_list };
         quest.Question_descr = "H ekfoonisi tis erotisis aytis einai blablbalbablbalblab";
         for (int i = 0; i < 10; i++)
         {
             question_list.Add(quest);
         }
     questionaire = new Quastionnaire.Model.Questionaire() { Questionaire_descr = "sdfsakdfjdflshsadflkjashflasdfkh", QuestionList = question_list };
     }
     //////////////////////////////////////////////////////////////////////
 }
Exemple #19
0
        public PrintPDFTicket(string selseatssend, string movienamesend, string scrnosend)
        {
            InitializeComponent();
            PdfDocument pdf = new PdfSharp.Pdf.PdfDocument();

            label1.Text = "Tickets printed.";
            pdfp        = pdf.AddPage();
            graph       = XGraphics.FromPdfPage(pdfp);
            XFont font_title  = new XFont("Franklin Gothic Heavy", 20, XFontStyle.Bold);
            XFont font_normal = new XFont("Segoe UI", 11, XFontStyle.Regular);

            writePdfText("SimPlex Cinemas", font_title, "Blue");
            y += 20;
            writePdfText("MOVIE TICKET | ADMIT ONE PER SEAT", font_normal, "Black");
            y += 10;
            writePdfText("Screen number: " + scrnosend, font_normal, "Black");
            y += 10;
            writePdfText("Movie name: " + movienamesend, font_normal, "Black");
            y += 10;
            writePdfText("Seat Number:" + selseatssend, font_normal, "Black");
            y += 20;
            writePdfText("Preserve ticket till end of show. All Rights Reserved.", font_normal, "Black");

            pdf.Save("FirstPDF.pdf");

            //label2.Text = "PDF creation completed";
        }
        /// <inheritdoc/>
        void Core2D.Interfaces.IProjectExporter.Save(string path, Core2D.Project.XDocument document)
        {
            using (var pdf = new PdfDocument())
            {
                var documentOutline = default(PdfOutline);

                foreach (var container in document.Pages)
                {
                    var page = Add(pdf, container);

                    if (documentOutline == null)
                    {
                        documentOutline = pdf.Outlines.Add(
                            document.Name,
                            page,
                            true,
                            PdfOutlineStyle.Regular,
                            XColors.Black);
                    }

                    documentOutline.Outlines.Add(
                        container.Name,
                        page,
                        true,
                        PdfOutlineStyle.Regular,
                        XColors.Black);
                }

                pdf.Save(path);
                ClearCache(isZooming: false);
            }
        }
Exemple #21
0
 public LayoutHelper(PdfDocument document, XUnit topPosition, XUnit bottomMargin)
 {
     _document        = document;
     _topPosition     = topPosition;
     _bottomMargin    = bottomMargin;
     _currentPosition = bottomMargin + 10000;
 }
Exemple #22
0
        private string SaveDocument(Document document)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding)
            {
                Document = document
            };
#pragma warning restore CS0618 // Type or member is obsolete

            // pdfRenderer = new PdfDocumentRenderer();
            pdfRenderer.RenderDocument();
            PdfSharp.Pdf.PdfDocument pdfdoc = pdfRenderer.PdfDocument;
            pdfdoc.ViewerPreferences.FitWindow = false;
            pdfdoc.PageLayout = PdfSharp.Pdf.PdfPageLayout.SinglePage;
            pdfdoc.PageMode   = PdfSharp.Pdf.PdfPageMode.UseNone;

            if (!System.IO.Directory.Exists(travelDocumentFolder))
            {
                System.IO.Directory.CreateDirectory(travelDocumentFolder);
            }

            string fileName = travelDocumentFolder + "\\CertificateOfInsurance.pdf";

            pdfRenderer.PdfDocument.Save(fileName);

            System.Diagnostics.Process.Start(fileName);

            return(fileName);
        }
Exemple #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PdfObject"/> class.
 /// </summary>
 protected PdfObject(PdfDocument document)
 {
     // Calling a virtual member in a constructor is dangerous.
     // In PDFsharp Document is overridden in PdfPage and the code is checked to be save
     // when called for a not completely initialized object.
     Document = document;
 }
Exemple #24
0
        public PdfDocument Render(IEnumerable<Page> pages, Unit pageWidth, Unit pageHeight)
        {
            var currentPageNumber = 1;
            var totalPageNumber = pages.Count();
            var document = new PdfDocument();
            foreach (var page in pages)
            {
                var canvas = AddPageTo(document, pageWidth, pageHeight);
                foreach (var element in page.Elements)
                {
                    borderRenderer.Render(canvas, element);

                    if (element.Specification is Backgrounded)
                        backgroundRenderer.Render(canvas, element);

                    if (element.Specification is Image)
                        imageRenderer.Render(canvas, element);

                    if (element.Specification is Text)
                        textRenderer.Render(canvas, element);
                }
                currentPageNumber++;
            }

            return document;
        }
Exemple #25
0
    /// <summary>
    /// Imports all pages from a list of documents.
    /// </summary>
    static void Variant1()
    {
      // Get some file names
      string[] files = GetFiles();

      // Open the output document
      PdfDocument outputDocument = new PdfDocument();

      // Iterate files
      foreach (string file in files)
      {
        // Open the document to import pages from it.
        PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);

        // Iterate pages
        int count = inputDocument.PageCount;
        for (int idx = 0; idx < count; idx++)
        {
          // Get the page from the external document...
          PdfPage page = inputDocument.Pages[idx];
          // ...and add it to the output document.
          outputDocument.AddPage(page);
        }
      }

      // Save the document...
      const string filename = "ConcatenatedDocument1_tempfile.pdf";
      outputDocument.Save(filename);
      // ...and start a viewer.
      Process.Start(filename);
    }
Exemple #26
0
    static void Main()
    {
      // Create a new PDF document
      PdfDocument document = new PdfDocument();
      document.Info.Title = "Created with PDFsharp";

      // Create an empty page
      PdfPage page = document.AddPage();

      // Get an XGraphics object for drawing
      XGraphics gfx = XGraphics.FromPdfPage(page);

      //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

      // Create a font
      XFont font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

      // Draw the text
      gfx.DrawString("Hello, World!", font, XBrushes.Black,
        new XRect(0, 0, page.Width, page.Height),
        XStringFormats.Center);

      // Save the document...
      const string filename = "HelloWorld_tempfile.pdf";
      document.Save(filename);
      // ...and start a viewer.
      Process.Start(filename);
    }
Exemple #27
0
        private void btnMultiplePDF_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.InitialDirectory = "C:\\PDFDemoTemp";
            dlg.Filter           = "JPEG files (*.jpg)|*.jpg|All files (*.*)|*.*";
            dlg.Multiselect      = true;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                PdfDocument document = new PdfDocument();
                document.Info.Title = "Created using PDFsharp";

                PdfPage   page   = document.AddPage();
                int       StartX = 0 - (int)page.Width / 2;
                int       StartY = 0 - (int)page.Height / 2;
                XGraphics gfx    = XGraphics.FromPdfPage(page);
                foreach (string fileSpec in dlg.FileNames)
                {
                    DrawImage(gfx, fileSpec, StartX, StartY, (int)page.Width * 2, (int)page.Height * 2);
                    StartX += (int)page.Width / 2;
                    StartY += (int)page.Height / 2;
                }
                if (document.PageCount > 0)
                {
                    document.Save(@"C:\PDFDemoTemp\ResultZoomInOnImage.pdf");
                }
            }
        }
        internal static byte[] GenerateApplicationPdf(Application application)
        {
            //Create pdf document
            PdfDocument pdf = new PdfDocument();
            PdfPage page = pdf.AddPage();
            //Create pdf content
            Document doc = CreateDocument("Application", string.Format("{1}, {0}",application.Person.Name, application.Person.Surname));
            PopulateDocument(ref doc, application);
            //Create renderer for content
            DocumentRenderer renderer = new DocumentRenderer(doc);
            renderer.PrepareDocument();
            XRect A4 = new XRect(0, 0, XUnit.FromCentimeter(21).Point, XUnit.FromCentimeter(29.7).Point);
            XGraphics gfx = XGraphics.FromPdfPage(page);

            int pages = renderer.FormattedDocument.PageCount;
            for(int i = 0; i < pages; i++)
            {
                var container = gfx.BeginContainer(A4, A4, XGraphicsUnit.Point);
                gfx.DrawRectangle(XPens.LightGray, A4);
                renderer.RenderPage(gfx, (i + 1));
                gfx.EndContainer(container);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                pdf.Save(ms, true);
                return ms.ToArray();
            }
        }
Exemple #29
0
        public static PdfDocument GetDocumentFromFiles(List<string> files, bool throwOnFail)
        {
            PdfDocument doc = new PdfDocument();
            doc.Info.Title = "";

            //TODO set some others here
            doc.Info.Elements.SetString("/Producer", "8labs Bulk Image To Pdf converter.");
            doc.Info.Elements.SetString("/Creator", "8labs Bulk Image To Pdf converter.");

            //TODO any sorting, etc... or should happen prior to this function
            foreach (string f in files)
            {
                try
                {
                    if (File.Exists(f)) //TODO more verification on what we're working on.
                    {
                        List<BitmapSource> imgs = ImgToPdf.GetImagesFromFile(f);
                        foreach (BitmapSource bmp in imgs)
                        {
                            //TODO handle scaling here for better results/speed than the pdf lib scaling??
                            //TODO convert to monochrome or otherwise compress?
                            AddImagePage(doc, bmp); //add a page of the image
                        }
                    }
                }
                catch (Exception)
                {
                    //only throw if specified
                    if (throwOnFail) throw;
                }

            }

            return doc;
        }
Exemple #30
0
        //PDFSharp - less features but same company as MigraDoc
        public PdfDocument ConvertToPdf2(ArrayList translationInput, int caseNumber, int evidenceNumber)
        {
            PdfDocument document = new PdfDocument();

            document.Info.Title = "Decrypted Translations";

            PdfSharp.Pdf.PdfPage page = document.AddPage();

            XGraphics gfx = XGraphics.FromPdfPage(page);

            XFont font = new XFont("Verdna", 11, XFontStyle.Regular);

            var    formatter = new PdfSharp.Drawing.Layout.XTextFormatter(gfx);
            var    rectangle = new XRect(10, 10, page.Width, page.Height);
            string newText   = "";
            //string newText2 = "";
            int i = 0;

            foreach (string text in translationInput)
            {
                i++;
                Console.WriteLine(i + " " + text);
                newText = newText + i + ". " + text + "\r\n";
            }
            formatter.DrawString(newText, font, XBrushes.Black, rectangle);

            string filename = "CsNum" + caseNumber + ".EviNum" + evidenceNumber + ".pdf";

            document.Save(filename);
            //Process.Start(filename);

            return(document);
        }
Exemple #31
0
        private void btnJPGtoPDF_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.InitialDirectory = "C:\\PDFDemoTemp";
            dlg.Filter           = "JPEG files (*.jpg)|*.jpg|All files (*.*)|*.*";
            dlg.Multiselect      = true;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                PdfDocument document = new PdfDocument();
                document.Info.Title = "Created using PDFsharp";

                foreach (string fileSpec in dlg.FileNames)
                {
                    PdfPage   page = document.AddPage();
                    XGraphics gfx  = XGraphics.FromPdfPage(page);
                    DrawImage(gfx, fileSpec, 0, 0, (int)page.Width, (int)page.Height);
                }
                if (document.PageCount > 0)
                {
                    document.Save(@"C: \Users\winst\Desktop\testResultOneImagePerPage.pdf");                          //경로가 절대 주소여서 바꿔줘야 합니다.
                }
            }
        }
Exemple #32
0
        public void Create(string filename, int qcount, int cellsinq, List<string> cellslabels,int rowscount)
        {
            s_document = new PdfDocument();

            _page = new PdfPage();
            _page.Orientation = PageOrientation.Landscape;
            _page.Size = PageSize.A4;
            s_document.Pages.Add(_page);
            gfx = XGraphics.FromPdfPage(_page);

            DrawCenterMarker(7);

            DrawSideMarker(7, 10, 10);
            DrawSideMarker(7, 285, 10);
            DrawSideMarker(7, 10, 200);
            DrawSideMarker(7, 285, 200);

            AddFields();

            AddQuestions(qcount,cellsinq,cellslabels,rowscount);

            // Save the s_document...
            s_document.Save(filename);
            // ...and start a viewer
            Process.Start(filename);
        }
Exemple #33
0
        private void btnFitPageToImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.InitialDirectory = "C:\\PDFDemoTemp";
            dlg.Filter           = "JPEG files (*.jpg)|*.jpg|All files (*.*)|*.*";
            dlg.Multiselect      = true;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                PdfDocument document = new PdfDocument();
                document.Info.Title = "Created using PDFsharp";

                PdfPage   page = document.AddPage();
                XGraphics gfx  = XGraphics.FromPdfPage(page);

                foreach (string fileSpec in dlg.FileNames)
                {
                    System.Drawing.Image img = System.Drawing.Image.FromFile(fileSpec);
                    page.Width  = img.Width;
                    page.Height = img.Height;
                    DrawImage(gfx, fileSpec, 0, 0, (int)page.Width, (int)page.Height);
                }
                if (document.PageCount > 0)
                {
                    document.Save(@"C:\PDFDemoTemp\ResultFitPageToImage.pdf");
                }
            }
        }
        // Here we setup the PDF page and then create our PDFGeoCanvas.
        // We loop through all the layers to draw and then save & pop the
        // PDF
        private void btnToPdf_Click(object sender, EventArgs e)
        {
            PdfDocument document = new PdfDocument();
            PdfPage page = document.AddPage();
            if (pageOrientationLandscape.IsChecked == true)
            {
                page.Orientation = PageOrientation.Landscape;
            }

            PdfGeoCanvas pdfGeoCanvas = new PdfGeoCanvas();

            // This allows you to control the area in which you want the
            // map to draw in.  Leaving this commented out uses the whole page
            //pdfGeoCanvas.DrawingArea = new Rectangle(200, 50, 400, 400);
            Collection<SimpleCandidate> labelsInLayers = new Collection<SimpleCandidate>();
            pdfGeoCanvas.BeginDrawing(page, wpfMap1.CurrentExtent, GeographyUnit.DecimalDegree);
            foreach (Layer layer in ((LayerOverlay)wpfMap1.Overlays[0]).Layers)
            {
                layer.Open();
                layer.Draw(pdfGeoCanvas, labelsInLayers);
                layer.Close();
            }
            pdfGeoCanvas.EndDrawing();
            string filename = GetTemporaryFolder() + "\\MapSuite PDF Map.pdf";
            try
            {
                document.Save(filename);
                OpenPdfFile(filename);
            }
            catch (Exception ex)
            {
                string message = "You have no permission to write file to disk." + ex.Message;
                MessageBox.Show(message, "No permission", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, (MessageBoxOptions)0);
            }
        }
Exemple #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Create a new PDF document
            PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();

            // Create an empty page
            PdfPage page = document.AddPage();
            //page.Contents.CreateSingleContent().Stream.UnfilteredValue;

            // Get an XGraphics object for drawing
            XGraphics gfx = XGraphics.FromPdfPage(page);

            Render(gfx);
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter           = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex      = 1;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                document.Save(saveFileDialog1.FileName);
                Process.Start(saveFileDialog1.FileName);
            }
        }
 public static XGraphics NewPage(PdfDocument document, XUnit width, XUnit height)
 {
     var page = document.AddPage();
     page.Width = width;
     page.Height = height;
     return XGraphics.FromPdfPage(page);
 }
Exemple #37
0
        private void splitPDF()
        {
            pathOfFolderWithSplittedPDFs = pathOfFolderOnDesktop + "\\3";
            System.IO.Directory.CreateDirectory(pathOfFolderWithSplittedPDFs);
            ////// Get a fresh copy of the sample PDF file
            //const string filename = "Portable Document Format.pdf";
            //File.Copy(Path.Combine("../../../../../PDFs/", filename),
            //Path.Combine(Directory.GetCurrentDirectory(), filename), true);
            string filename = pathOfFolderWithMergedPDF + "\\Merge.pdf";

            // Open the file
            PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfDocumentOpenMode.Import);
            string name = Path.GetFileNameWithoutExtension(filename);

            for (int idx = 0; idx < inputDocument.PageCount; idx++)
            {
                // Create new document
                PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();
                outputDocument.Version    = inputDocument.Version;
                outputDocument.Info.Title =
                    String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
                //outputDocument.Info.Creator = inputDocument.Info.Creator;

                // Add the page and save it
                outputDocument.AddPage(inputDocument.Pages[idx]);
                outputDocument.Save(pathOfFolderWithSplittedPDFs + "\\" + String.Format("{0} - Page {1}_tempfile.pdf", idx + 1, name));
            }
        }
Exemple #38
0
        public byte[] MergePdfs(IEnumerable<FileToMerge> files)
        {
            byte[] mergedPdfContents;

            using (var mergedPdfDocument = new PdfDocument())
            {
                foreach (var file in files)
                {
                    using (var memoryStream = new MemoryStream(file.Contents))
                    {
                        var inputPdfDocument = PdfReader.Open(memoryStream, PdfDocumentOpenMode.Import);

                        var pageCount = inputPdfDocument.PageCount;
                        for (var pageNumber = 0; pageNumber < pageCount; pageNumber++)
                        {
                            var page = inputPdfDocument.Pages[pageNumber];
                            mergedPdfDocument.AddPage(page);
                        }
                    }
                }

                using (var mergedPdfStream = new MemoryStream())
                {
                    mergedPdfDocument.Save(mergedPdfStream);

                    mergedPdfContents = mergedPdfStream.ToArray();
                }
            }

            return mergedPdfContents;
        }
Exemple #39
0
 private void CopyPages(PdfSharp.Pdf.PdfDocument from, PdfSharp.Pdf.PdfDocument to)
 {
     for (int i = 0; i < from.PageCount; i++)
     {
         to.AddPage(from.Pages[i]);
     }
 }
Exemple #40
0
        public Uri GetCookBook(string name)
        {
            var document = new PdfDocument();
            document.Info.Title = name + "'s personalized cookbook";
            document.Info.Author = "Pancake Prowler";

            var page = document.AddPage();

            var graphics = XGraphics.FromPdfPage(page);

            var font = new XFont("Verdana", 20, XFontStyle.BoldItalic);

            graphics.DrawString(name + "'s personalized cookbook",
                font,
                XBrushes.Red,
                new System.Drawing.PointF((float)page.Width / 2, (float)page.Height / 2),
                XStringFormats.Center);

            var saveStream = new MemoryStream();
            document.Save(saveStream);

            var memoryStream = new MemoryStream(saveStream.ToArray());
            memoryStream.Seek(0, SeekOrigin.Begin);

            var imageStore = new BlobImageRepository();
            return imageStore.Save("application/pdf", memoryStream, "cookbooks");
        }
    /// <summary>
    /// Parses the given XPS file and saves the PDF Version.
    /// </summary>
    void ParseFile(string file)
    {
      string baseDir = "../../../PdfSharp.Xps.UnitTests/Primitives.Glyphs/GlyphFiles";

      string filename = System.IO.Path.Combine(baseDir, file + ".xps");

      PdfDocument document = new PdfDocument();

      try
      {
        XpsModel.XpsDocument xpsDoc = XpsModel.XpsDocument.Open(filename);
        foreach (XpsModel.FixedDocument doc in xpsDoc.Documents)
        {
          foreach (XpsModel.FixedPage page in doc.Pages)
          {
            page.GetType();

            //Render PDF Page
            PdfPage pdfpage = document.AddPage();
            pdfpage.Width = WidthInPoint;
            pdfpage.Height = HeightInPoint;

            PdfRenderer renderer = new PdfRenderer();
            renderer.RenderPage(pdfpage, page);

          }
        }
      }
      catch (Exception ex)
      {
        Debug.WriteLine(ex.Message);
        GetType();
      }
      document.Save(Path.Combine(OutputDirectory, file + ".pdf"));
    }
Exemple #42
0
        public string ParsearPDF()
        {
            string storageConnectionString         = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
            string azureFolderPath                 = "";
            CloudStorageAccount storageAccount     = CloudStorageAccount.Parse(storageConnectionString);
            CloudBlobClient     blobClient         = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container          = blobClient.GetContainerReference("carpetapdf");
            CloudBlobDirectory  cloudBlobDirectory = container.GetDirectoryReference(azureFolderPath);

            ////get source file to split
            string         pdfFile    = "pliego.pdf";
            CloudBlockBlob blockBlob1 = cloudBlobDirectory.GetBlockBlobReference(pdfFile);

            //convert to memory stream
            MemoryStream memStream = new MemoryStream();

            blockBlob1.DownloadToStreamAsync(memStream).Wait();


            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

            //get source file to split
            for (var i = 0; i <= doc.Pages.Count - 1; i++)
            {
                //define output file for azure
                string         outputPDFFile   = "output" + i + ".pdf";
                CloudBlockBlob outputblockBlob = cloudBlobDirectory.GetBlockBlobReference(outputPDFFile);

                //create new document
                MemoryStream newPDFStream = new MemoryStream();

                PdfSharp.Pdf.PdfDocument pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(strOriginal, PdfDocumentOpenMode.Import);

                for (var j = doc.Pages.Count - 1; j >= 0; j--)
                {
                    if (j != i)
                    {
                        pdfDoc.Pages.RemoveAt(j);
                    }
                }



                byte[] pdfData;
                using (var ms = new MemoryStream())
                {
                    //doc.Save(ms);
                    pdfDoc.Save(ms);
                    pdfData = ms.ToArray();



                    //outputblockBlob.UploadFromStreamAsync(ms);
                    outputblockBlob.UploadFromByteArrayAsync(pdfData, 0, pdfData.Length);
                }
            }

            return("Ok");
        }
Exemple #43
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;

            List <int> pageIndexes = new List <int>();

            for (int i = 0; i < lvPages.Items.Count; i++)
            {
                if (lvPages.Items[i].Checked)
                {
                    pageIndexes.Add(i);
                }
            }

            /*Bitmap[] bmps = MupdfSharp.PageRenderer.Render(path, PAGETHEIGHTPIXEL, pageIndexes.ToArray());
             * for(int i = 0; i < bmps.Length; i++)
             * {
             *  Bitmap tmp = bmps[i];
             *  bmps[i] = tmp.MakeBackgroundTransparent(Color.White);
             *  tmp.Dispose();
             * }*/

            if (!Directory.Exists(TmpManager.GetTmpDir() + "\\render"))
            {
                Directory.CreateDirectory(TmpManager.GetTmpDir() + "\\render");
            }

            Pages = new KPage[pageIndexes.Count];
            pdf.PdfDocument pdfdoc = pdf_io.PdfReader.Open(path, pdf_io.PdfDocumentOpenMode.Modify | pdf_io.PdfDocumentOpenMode.Import);

            for (int i = 0; i < pageIndexes.Count; i++)
            {
                int         p     = pageIndexes[i];
                KPage       page  = new KPage(KDocument.EmptyDocument);
                pdf.PdfPage pPage = pdfdoc.Pages[p];
                float       w     = (float)pPage.Width.Millimeter;
                float       h     = (float)pPage.Height.Millimeter;
                if (pPage.Rotate == 90 || pPage.Rotate == 270)
                {
                    Util.Swap(ref w, ref h);
                }
                page.Format       = new PageFormat(w, h);
                page.Background   = null;
                page.ShowDate     = false;
                page.OriginalPage = pPage;

                /*page.BackgroundImage
                 *  = new Renderer.Image(bmps[i]);*/

                page.PdfRenderPath = TmpManager.NewFilename(TmpManager.GetTmpDir() + "\\render", "page", ".png");
                Pages[i]           = page;
            }
            pdfdoc.Close();
        }
Exemple #44
0
        public MemoryStream Message2Pdf(MimeMessage message)
        {
            MemoryStream msMail = new MemoryStream();
            string       html   = message.GetTextBody(MimeKit.Text.TextFormat.Html);
            string       txt    = message.GetTextBody(MimeKit.Text.TextFormat.Text);

            HtmlToPdf converter = new HtmlToPdf();

            SelectPdf.PdfDocument pdfdok = null;
            if (html != null)
            {
                pdfdok = converter.ConvertHtmlString(html);
            }
            else
            {
                if (string.IsNullOrEmpty(txt))
                {
                    txt = "Tom email";
                }
                pdfdok = converter.ConvertHtmlString(txt);
            }
            pdfdok.Save(msMail);
            msMail.Position = 0;

            XPdfForm form = XPdfForm.FromStream(msMail);

            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();
            XGraphics gfx;

            int count = form.PageCount;

            for (int idx = 0; idx < count; idx++)
            {
                PdfSharp.Pdf.PdfPage page = outputDocument.AddPage();
                if (form.PageCount > idx)
                {
                    // Get a graphics object for page
                    gfx = XGraphics.FromPdfPage(page);
                    if (idx == 0)
                    {
                        DrawPageHeading(page, gfx, message);
                        // Draw the page like an image
                        gfx.DrawImage(form, new XRect(form.PointWidth * 0.02, form.PointHeight * 0.10, form.PointWidth * 0.90, form.PointHeight * 0.90));
                    }
                    else
                    {
                        gfx.DrawImage(form, new XRect(form.PointWidth, form.PointHeight, form.PointWidth, form.PointHeight));
                    }
                }
            }
            msMail = new MemoryStream();
            outputDocument.Save(msMail, false);
            return(msMail);
        }
Exemple #45
0
        private static double TamanhoTexto(string nome, double fontSize)
        {
            var pdfDoc  = new PdfSharp.Pdf.PdfDocument();
            var pdfPage = pdfDoc.AddPage();
            var pdfGfx  = PdfSharp.Drawing.XGraphics.FromPdfPage(pdfPage);
            var pdfFont = new PdfSharp.Drawing.XFont("Times New Roman", fontSize);
            var tamanho = pdfGfx.MeasureString(nome, pdfFont).Width;

            return(tamanho);

            //pdfGfx.DrawString("Hello World!", pdfFont, PdfSharp.Drawing.XBrushes.Black, new PdfSharp.Drawing.XPoint(100, 100));
        }
Exemple #46
0
        public MainWindow()
        {
            InitializeComponent();

            //test();

            var pdfReader = PdfReader.Open(pdfFile);

            PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument(pdfFile);
            //PdfSharp.Pdf.Advanced.PdfImage img = new PdfSharp.Pdf.Advanced.PdfImage(doc, img);
            //PdfView.Source = new Uri(pdfFile);
        }
        public string Convert(List <PDFInfo> listPDFInfo, string outputFolder, string outputFilename)
        {
            List <string> listFileTemp = new List <string>();

            try
            {
                PdfSharp.Pdf.PdfDocument outputPDFDocument = new PdfSharp.Pdf.PdfDocument();
                string fileCombine = outputFolder + @"\" + (!string.IsNullOrWhiteSpace(outputFilename) ? outputFilename.Trim() : Guid.NewGuid().ToString()) + ".pdf";
                listPDFInfo = listPDFInfo.OrderBy(x => x.Order).ToList();

                if (!Directory.Exists(outputFolder))
                {
                    Directory.CreateDirectory(outputFolder);
                }

                ConvertToPDF convertToPDF = new ConvertToPDF();
                foreach (var item in listPDFInfo)
                {
                    string fileTemp = outputFolder + @"\" + Guid.NewGuid().ToString() + Path.GetFileName(item.FilePDF);
                    File.Copy(item.FilePDF, fileTemp);
                    listFileTemp.Add(fileTemp);
                    if (item.Rotate != 0)
                    {
                        convertToPDF.RotatePDF(fileTemp, item.Rotate);
                    }
                    PdfSharp.Pdf.PdfDocument inputPDFDocument = PdfSharp.Pdf.IO.PdfReader.Open(fileTemp, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
                    outputPDFDocument.Version = inputPDFDocument.Version;
                    foreach (PdfSharp.Pdf.PdfPage page in inputPDFDocument.Pages)
                    {
                        outputPDFDocument.AddPage(page);
                    }
                }
                outputPDFDocument.Save(fileCombine);

                return(fileCombine);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (listFileTemp.Count > 0)
                {
                    listFileTemp.ForEach(item => { if (File.Exists(item))
                                                   {
                                                       File.Delete(item);
                                                   }
                                         });
                }
            }
        }
 ///<summary>This function set the compression parameters of PDF document</summary>
 ///<param name="pdfDoc"></param>
 ///<author>Anubhav Passi, Date - 2/3/2018</author>
 public static void CompressMyPdf(PdfSharp.Pdf.PdfDocument pdfDoc, String directory)
 {
     try
     {
         // Code for PDF Compression
         pdfDoc.Options.NoCompression   = false;
         pdfDoc.Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
         pdfDoc.Options.UseFlateDecoderForJpegImages           = PdfUseFlateDecoderForJpegImages.Automatic;
         pdfDoc.Options.EnableCcittCompressionForBilevelImages = true;
         pdfDoc.Options.CompressContentStreams = true;
         pdfDoc.Save(directory);
     }
     catch (Exception e)
     {
     }
 }
 public static void MergePDFs(string targetPath, params string[] pdfs)
 {
     // -------- Unir todos los PDFs de la ruta en uno solo --------
     using (PdfSharp.Pdf.PdfDocument targetDoc = new PdfSharp.Pdf.PdfDocument()) {
         foreach (string pdf in pdfs)
         {
             using (PdfSharp.Pdf.PdfDocument pdfDoc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import)) {
                 for (int i = 0; i < pdfDoc.PageCount; i++)
                 {
                     targetDoc.AddPage(pdfDoc.Pages[i]);
                 }
             }
         }
         targetDoc.Save(targetPath);
     }
 }
        public async Task GeneratePdf2(string html, string filePath)
        {
            await Task.Run(() =>
            {
                using (FileStream ms = new FileStream(filePath, FileMode.Create))
                {
                    XImage xImage = XImage.FromFile(@"D:\Logo.png");
                    PdfSharp.Pdf.PdfDocument pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
                    PdfPage page  = pdf.Pages[0];
                    XGraphics gfx = XGraphics.FromPdfPage(page);
                    gfx.DrawImage(xImage, 0, 0, xImage.PixelWidth, xImage.PixelHeight);

                    pdf.Save(ms);
                }
            });
        }
Exemple #51
0
        public static void DrawBeziers()
        {
            string fn = @"input.pdf";

            using (PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(fn))
            {
                // Create an empty XForm object with the specified width and height
                // A form is bound to its target document when it is created. The reason is that the form can
                // share fonts and other objects with its target document.
                using (XForm form = new XForm(document, XUnit.FromMillimeter(70), XUnit.FromMillimeter(55)))
                {
                    // Create an XGraphics object for drawing the contents of the form.
                    using (XGraphics formGfx = XGraphics.FromForm(form))
                    {
                        // Draw a large transparent rectangle to visualize the area the form occupies
                        XColor back = XColors.Orange;
                        back.A = 0.2;
                        XSolidBrush brush = new XSolidBrush(back);
                        formGfx.DrawRectangle(brush, -10000, -10000, 20000, 20000);

                        // On a form you can draw...

                        // ... text
                        formGfx.DrawString("Text, Graphics, Images, and Forms", new XFont("Verdana", 10, XFontStyle.Regular), XBrushes.Navy, 3, 0, XStringFormats.TopLeft);
                        XPen pen = XPens.LightBlue.Clone();
                        pen.Width = 2.5;

                        // ... graphics like Bézier curves
                        formGfx.DrawBeziers(pen, XPoint.ParsePoints("30,120 80,20 100,140 175,33.3"));

                        // ... raster images like GIF files
                        XGraphicsState state = formGfx.Save();
                        formGfx.RotateAtTransform(17, new XPoint(30, 30));
                        formGfx.DrawImage(XImage.FromFile("../../../../../../dev/XGraphicsLab/images/Test.gif"), 20, 20);
                        formGfx.Restore(state);

                        // ... and forms like XPdfForm objects
                        state = formGfx.Save();
                        formGfx.RotateAtTransform(-8, new XPoint(165, 115));
                        formGfx.DrawImage(XPdfForm.FromFile("../../../../../PDFs/SomeLayout.pdf"), new XRect(140, 80, 50, 50 * System.Math.Sqrt(2)));
                        formGfx.Restore(state);

                        // When you finished drawing on the form, dispose the XGraphic object.
                    } // End Using formGfx
                }     // End Using form
            }         // End Using document
        }
Exemple #52
0
        public byte[] CreatePdf(byte inputs)
        {
            var     document = new PdfDocument();
            PdfPage page     = document.AddPage();
            var     gtx      = XGraphics.FromPdfPage(page);
            var     font     = new XFont("Verdana", 20, XFontStyle.Bold);

            gtx.DrawString("Hello, World!", font, XBrushes.Black,
                           new XRect(0, 0, page.Width, page.Height),
                           XStringFormats.Center);

            string fileName = "HelloWorld.pdf";

            document.Save(fileName);

            return(new byte[1]);
        }
Exemple #53
0
        private void btnHello_Click(object sender, EventArgs e)
        {
            PdfDocument document = new PdfDocument();

            document.Info.Title = "Created with PDFsharp";
            PdfPage page = document.AddPage();
            //page.Size = PdfSharp.PageSize.A5;
            XGraphics gfx  = XGraphics.FromPdfPage(page);
            XFont     font = new XFont("Verdana", 20, XFontStyle.BoldItalic);

            gfx.DrawString("Hello, World!", font, XBrushes.Black,
                           new XRect(0, 0, page.Width, page.Height),
                           XStringFormats.Center);
            const string filename = "c:\\PDFDemoTemp\\ResultHelloWorld.pdf";

            document.Save(filename);
        }
Exemple #54
0
        private void comPDF0(List <string> filelist, string path0)
        {
            Sharp.PdfDocument outputDocument = new Sharp.PdfDocument();
            outputDocument.PageLayout = Sharp.PdfPageLayout.TwoColumnLeft;
            foreach (string f in filelist)
            {
                Sharp.PdfDocument inputDocument = SharpIO.PdfReader.Open(f, SharpIO.PdfDocumentOpenMode.Import);
                int count = inputDocument.PageCount;
                for (int idx = 0; idx < count; idx++)
                {
                    Sharp.PdfPage page = inputDocument.Pages[idx];
                    outputDocument.AddPage(page);
                }
                inputDocument.Close();
            }
            string filename = path0;

            outputDocument.Save(filename);
        }
    public static void ToPDF(IEnumerable <Account> accounts)
    {
        var pdfDocument = new PDF.Pdf.PdfDocument();

        pdfDocument.Info.Title = "Account data";        // get it from outside
        var page  = pdfDocument.AddPage();
        var gfx   = PDF.Drawing.XGraphics.FromPdfPage(page);
        var font  = new PDF.Drawing.XFont("Verdana", 14, PDF.Drawing.XFontStyle.BoldItalic);
        int yAxis = 40;

        foreach (var acct in accounts)
        {
            gfx.DrawString($"ID: {acct.ID}, Balance: {acct.Balance}", font, PDF.Drawing.XBrushes.Black, new PDF.Drawing.XRect(40, yAxis, 250, 40 + yAxis), PDF.Drawing.XStringFormats.TopLeft);    // fix it
            yAxis += 20;
        }
        const string filename = "Accounts.pdf";

        pdfDocument.Save(filename);
        System.Diagnostics.Process.Start(@AppDomain.CurrentDomain.BaseDirectory + "\\Accounts.pdf");
    }
        public async Task GeneratePdf(string html, string filePath)
        {
            await Task.Run(() =>
            {
                using (FileStream ms = new FileStream(filePath, FileMode.Create))
                {
                    PdfSharp.Pdf.PdfDocument pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
                    pdf.Save(ms);
                    ms.Close();
                }
                Spire.Pdf.PdfDocument abc         = new Spire.Pdf.PdfDocument(filePath);
                Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile(@"D:\Logo.png");
                float width  = image.Width * 0.75f;
                float height = image.Height * 0.75f;

                Spire.Pdf.PdfPageBase page0 = abc.Pages[0];
                float x = (page0.Canvas.ClientSize.Width - width) / 2;
                page0.Canvas.DrawImage(image, x, 60, width, height);
                abc.SaveToFile(filePath);
            });
        }
Exemple #57
0
        //2
        private void MergenAllPDFsIntoOnePDF_Click(object sender, EventArgs e)
        {
            PdfSharp.Pdf.PdfDocument onePdf;
            PdfSharp.Pdf.PdfDocument outPdf = new PdfSharp.Pdf.PdfDocument();
            pathOfFolderWithMergedPDF = pathOfFolderOnDesktop + "\\2";
            System.IO.Directory.CreateDirectory(pathOfFolderWithMergedPDF);

            DirectoryInfo toChange = new DirectoryInfo(pathOfFolderWithAllNumberedPDFs);

            foreach (var fi in toChange.GetFiles().OrderBy(fi => fi.Name))
            {
                onePdf = PdfSharp.Pdf.IO.PdfReader.Open(fi.FullName, PdfDocumentOpenMode.Import);
                CopyPages(onePdf, outPdf);
                onePdf.Close();
                //fi.Delete();
            }
            outPdf.Save(pathOfFolderWithMergedPDF + "\\" + "Merge.pdf");
            outPdf.Close();
            MessageBox.Show("Alle Zeichnungen werden in" + pathOfFolderWithMergedPDF + " Merge.pdf zusammengefügt", "My Application", MessageBoxButtons.OK, MessageBoxIcon.Question);
            EnableOnlyOneButton(btnNameChange);
        }
Exemple #58
0
        private void button1_Click(object sender, EventArgs e)
        {
            string pdfPath = "/";                                                  //PDF 경로
            string pdfname = "test.pdf";                                           //PDF 파일 이름

            string[]    jpgFiles = System.IO.Directory.GetFiles(pdfPath, "*.jpg"); //파일 읽어옴
            PdfDocument document = new PdfDocument();

            document.Info.Title = "Created using PDFsharp";

            for (int i = 0; i < jpgFiles.Length; i++)
            {
                PdfPage   page = document.AddPage();
                XGraphics gfx  = XGraphics.FromPdfPage(page);
                DrawImage(gfx, jpgFiles[i], 0, 0, (int)page.Width, (int)page.Height);
            }
            if (document.PageCount > 0)
            {
                document.Save(pdfPath + pdfname);
            }
        }
Exemple #59
-2
 private void OpenFile(int firstPage, int lastPage, PdfDocument pdfDocument)
 {
     for (int page = firstPage; page < lastPage; page++)
     {
         document.AddPage(pdfDocument.Pages[page]);
     }
 }
Exemple #60
-4
        public Book(string pathToBook)
        {
            if (string.IsNullOrEmpty(pathToBook))
                throw new ArgumentException("Invalid argument", "pathToBook");

            _pdfDocument = PdfReader.Open(pathToBook, PdfDocumentOpenMode.InformationOnly);
        }