Example #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);
    }
Example #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));
      }
    }
Example #3
0
    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();
    }
Example #4
0
        public Stream CreatePDF()
        {
            using (PdfDocument doc = new PdfDocument())
            {
                ScanImages((image) =>
                {
                    using (XImage ximage = XImage.FromGdiPlusImage(image))
                    {
                        PdfPage page = doc.AddPage();
                        page.Width = XUnit.FromInch(this.settings.PageSize.Width);
                        page.Height = XUnit.FromInch(this.settings.PageSize.Height);
                        using (XGraphics xgraphics = XGraphics.FromPdfPage(page))
                        {
                            xgraphics.DrawImage(ximage, 0, 0);
                        }
                    }
                });

                if (doc.PageCount > 0)
                {
                    var response = new MemoryStream();
                    doc.Save(response, false);
                    return response;
                }
                else
                {
                    throw new ScanException("Nothing was scanned.");
                }
            }
        }
Example #5
0
File: Form1.cs Project: jflzbest/C-
        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);
            }
        }
Example #6
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);
        }
Example #7
0
        public void Save (PdfDocument document)
        {
            // Save the document...  
            var filename = Path.Combine(ServerProperty.MapPath("~/Resources/PDF"), "test.pdf");
            document.Save(filename);

        }
        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();
            }
        }
Example #9
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());
                    }
                }
            }
        }
Example #10
0
 public static void CreatePdf(Sheet sheet,string fullFileName)
 {
     PdfDocument document=new PdfDocument();
     PdfPage page=document.AddPage();
     CreatePdfPage(sheet,page);
     document.Save(fullFileName);
 }
Example #11
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");
                }
            }
        }
Example #12
0
    //private PdfHelper()
    //{
    //}

    //public static PdfHelper Instance { get; } = new PdfHelper();

    internal void SaveImageAsPdf(string imageFileName, string pdfFileName, int width = 600, bool deleteImage = false)
    {
        using (var document = new PdfSharp.Pdf.PdfDocument())
        {
            PdfSharp.Pdf.PdfPage page = document.AddPage();
            using (XImage img = XImage.FromFile(imageFileName))
            {
                // Calculate new height to keep image ratio
                var height = (int)(((double)width / (double)img.PixelWidth) * img.PixelHeight);

                // Change PDF Page size to match image
                page.Width  = width;
                page.Height = height;

                XGraphics gfx = XGraphics.FromPdfPage(page);
                gfx.DrawImage(img, 0, 0, width, height);
            }
            var PtPosition  = imageFileName.LastIndexOf('.');
            var PathTemp    = imageFileName.Remove(PtPosition);
            var pathPdfFile = PathTemp + ".pdf";
            document.Save(pathPdfFile /*pdfFileName*/);
        }

        if (deleteImage)
        {
            File.Delete(imageFileName);
        }
    }
Example #13
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");
        }
Example #14
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);
    }
Example #15
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);
    }
Example #16
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);
        }
 public bool Convert(string inputFileName, string outputFileName)
 {
     try
     {
         using (PdfDocument doc = new PdfDocument())
         {
             PdfPage page = doc.AddPage();
             using (XGraphics gfx = XGraphics.FromPdfPage(page))
             using (var image = XImage.FromFile(inputFileName))
             {
                 var border = 10;
                 var widthRatio = (gfx.PageSize.Width - border * 2) / image.PixelWidth;
                 var heightRatio = (gfx.PageSize.Height - border) / image.PixelHeight;
                 var scaling = Math.Min(widthRatio, heightRatio);
                 gfx.DrawImage(image, border, border, image.PixelWidth * scaling, image.PixelHeight * scaling);
                 doc.Save(outputFileName);
             }
         }
         return true;
     }
     catch (Exception ex)
     {
         Logger.WarnFormat(ex, "Error converting file {0} to Pdf.", inputFileName);
         return false;
     }
 }
Example #18
0
    /// <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"));
    }
Example #19
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;
        }
Example #20
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);
    }
        /// <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);
            }
        }
        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);
        }
Example #23
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");
        }
Example #24
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));
            }
        }
Example #25
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);
                }
            }
        }
Example #26
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");
        }
 /// <inheritdoc/>
 void Core2D.Interfaces.IProjectExporter.Save(string path, Core2D.Project.XContainer container)
 {
     using (var pdf = new PdfDocument())
     {
         Add(pdf, container);
         pdf.Save(path);
     }
 }
Example #28
0
		public void Run (Stream stream) {
			if (stream == null)
				throw new ArgumentNullException("stream");
			pdfDocument = new PdfDocument(stream);
			ConvertPagesToPdf();
			pdfDocument.Save(stream,false);
			stream.Seek(0, SeekOrigin.Begin);
		}
Example #29
0
 public void Save(string path, ICanvas canvas)
 {
     using (var document = new PdfDocument())
     {
         AddPage(document, canvas);
         document.Save(path);
     }
 }
Example #30
0
 public void Save(string path, IEnumerable<ICanvas> canvases)
 {
     using (var document = new PdfDocument())
     {
         foreach (var canvas in canvases)
         {
             AddPage(document, canvas);
         }
         document.Save(path);
     }
 }
Example #31
0
    public void TestExternalXpsFiles()
    {
      string currentDirectory = Directory.GetCurrentDirectory();
#if true
      string[] files = Directory.GetFiles("../../../../../testing/PdfSharp.Xps.UnitTests/xternal", "*.xps", SearchOption.AllDirectories);
#else
      string[] files = Directory.GetFiles("../../../XPS-TestDocuments", "*.xps", SearchOption.AllDirectories);
#endif
      
      if (files.Length == 0)
        throw new Exception("No sample file found.");

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

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

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

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

            pdfDoc.Save(pdfFilename);
            docIndex++;
          }
        }
        catch (Exception ex)
        {
          Debug.WriteLine(ex.Message);
          GetType();
        }
      }
    }
Example #32
0
        public static void exportPage(PdfDocument currentDocument, int index, String outputFolder)
        {
            if (currentDocument == null)
                return;

            PdfDocument singlePage = new PdfDocument();
            singlePage.AddPage(currentDocument.Pages[index]);
            if (outputFolder != "")
                outputFolder += "\\";
            singlePage.Save(outputFolder + "page_" + Convert.ToString(index + 1) + ".pdf");
        }
Example #33
0
 private static byte[] ConvertPDFToBytes(PdfDocument document)
 {
     using (Stream stream = new MemoryStream())
     {
         //false says do not close stream - i will use it
         document.Save(stream, false);
         byte[] data = new byte[stream.Length];
         stream.Read(data, 0, (int)stream.Length);
         return data;
     }
 }
Example #34
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);
        }
Example #35
0
		public void Run (string fileName,bool show) {
			if (String.IsNullOrEmpty(fileName)) {
				fileName = Pages[0].PageInfo.ReportName + ".pdf";
			}
			pdfDocument = new PdfDocument();
			ConvertPagesToPdf();
			pdfDocument.Save(fileName);
			if (show) {
				Process.Start(fileName);	
			}	
		}
Example #36
0
 public static void Print(SongData song, string filename)
 {
     PdfDocument doc = new PdfDocument();
     PdfPage page = doc.AddPage();
     LogPages pages = SongPrinter.FormatSongForPrinting(song, PageSizeConverter.ToSize(page.Size).Width, PdfPrintTarget.InfoContext, PageSizeConverter.ToSize(page.Size).Height, PdfPrintTarget.getmmky());
     foreach (LogPage lp in pages.Pages)
     {
         lp.DrawPage(XGraphics.FromPdfPage(page), new PointF(0, 0), null);
         if (pages.LastPage != lp) page = doc.AddPage();
     }
     doc.Save(filename);
 }
Example #37
0
 public static string CopyFile(string fileName,string newFileName)
 {
     PdfDocument pdfDoc = PdfReader.Open(fileName, PdfDocumentOpenMode.Import);
     PdfDocument newDocument = new PdfDocument();
     for (int page = 0; page < pdfDoc.PageCount; page++)
     {
         newDocument.AddPage(pdfDoc.Pages[page]);
     }
     string path = newFileName + Path.GetExtension(fileName);
     newDocument.Save(path);
     return path;
 }
Example #38
0
 public void DrawString_SpecialCharacters()
 {
     var doc = new PdfDocument();
     doc.Options.NoCompression = true;
     doc.Options.CompressContentStreams = false;
     doc.Options.ColorMode = PdfColorMode.Rgb;
     var page = doc.AddPage();
     var g = XGraphics.FromPdfPage(page);
     var font = new XFont("Arial", 96);
     g.DrawString("π θ", font, XBrushes.Black, 200, 400);
     doc.Save(Folder + "DrawString_SpecialCharacters.pdf");
 }
Example #39
0
        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 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);
                }
            });
        }
 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);
     }
 }
Example #43
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]);
        }
Example #44
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);
        }
Example #45
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);
            });
        }
Example #48
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);
            }
        }
Example #49
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);
        }
Example #50
0
        public void MergePdfs(string[] inputs)
        {
            var outPdfDocument = new PdfDocument();

            foreach (var pdf in inputs)
            {
                var inputDocument = PdfReader.Open(pdf, PdfDocumentOpenMode.Import);
                outPdfDocument.Version = inputDocument.Version;

                foreach (var page in inputDocument.Pages)
                {
                    outPdfDocument.AddPage(page);
                }
            }

            var name = "WTF.pdf";

            outPdfDocument.Info.Creator = string.Empty;
            outPdfDocument.Save($"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}/lens.pdf");

            Process.Start(name);
        }
Example #51
0
        private void comPDF0(String filename1, String filename2, String out3)
        {
            Sharp.PdfDocument inputDocument1 = SharpIO.PdfReader.Open(filename1, SharpIO.PdfDocumentOpenMode.Import);
            Sharp.PdfDocument inputDocument2 = SharpIO.PdfReader.Open(filename2, SharpIO.PdfDocumentOpenMode.Import);
            Sharp.PdfDocument outputDocument = new Sharp.PdfDocument();
            // Show consecutive pages facing. Requires Acrobat 5 or higher.
            outputDocument.PageLayout = Sharp.PdfPageLayout.TwoColumnLeft;
            int count = Math.Max(inputDocument1.PageCount, inputDocument2.PageCount);

            for (int idx = 0; idx < count; idx++)
            {
                Sharp.PdfPage page1 = inputDocument1.PageCount > idx ?
                                      inputDocument1.Pages[idx] : new Sharp.PdfPage();
                Sharp.PdfPage page2 = inputDocument2.PageCount > idx ?
                                      inputDocument2.Pages[idx] : new Sharp.PdfPage();

                // Add both pages to the output document
                page1 = outputDocument.AddPage(page1);
                page2 = outputDocument.AddPage(page2);
            }
            string filename = out3;

            outputDocument.Save(filename);
        }
Example #52
0
        // create charges file
        public void CreateCharges(string nom, string prenom, string niveau)
        {
            // Create a new PDF document

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

            document.Info.Title = "Created with PDFsharp";
            // Create an empty page
            PdfSharp.Pdf.PdfPage page = document.AddPage();
            // Get an XGraphics object for drawing
            page.Size        = PageSize.A5;
            page.Orientation = PageOrientation.Landscape;
            XGraphics gfx = XGraphics.FromPdfPage(page);

            // Create a font
            XFont fonti = new XFont("Verdana", 20, XFontStyle.Regular);
            XFont font  = new XFont("Verdana", 16, XFontStyle.Regular);
            XFont fonta = new XFont("Verdana", 12, XFontStyle.Regular);

            // create an image
            string       fileLocation = System.IO.Path.Combine(Environment.CurrentDirectory, @"Bridges.png");
            XImage       img = XImage.FromFile(fileLocation);
            const double tx = 190, ty = 100, txa = 1010;
            double       wid = img.PixelWidth * 18 / img.HorizontalResolution;
            double       hei = img.PixelHeight * 18 / img.HorizontalResolution;

            gfx.DrawImage(img, (tx - wid) / 2, (ty - hei) / 2, wid, hei);
            gfx.DrawImage(img, (txa - wid) / 2, (ty - hei) / 2, wid, hei);

            // Draw the text
            gfx.DrawString("Bridges Of Knowledge Center", font, XBrushes.Black, new XRect(0, -160, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("Nom: " + nom, font, XBrushes.Black, new XRect(-(180 - nom.Length * 4), -50, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("Prenom: " + prenom, font, XBrushes.Black, new XRect(-(168 - prenom.Length * 4), -10, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("Niveau: " + niveau, font, XBrushes.Black, new XRect(-(172 - niveau.Length * 4), 30, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("Paiement: 400 DZD", font, XBrushes.Black, new XRect(-162, 70, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("Le : " + DateTime.Now.ToString("dd/MM/yyyy", new CultureInfo("fr-FR")), fonta, XBrushes.Black, new XRect(180, 120, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("à : " + DateTime.Now.ToString("hh:mm tt"), fonta, XBrushes.Black, new XRect(174, 140, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("© " + DateTime.Now.Year + ".", fonta, XBrushes.Black, new XRect(0, 200, page.Width, page.Height), XStringFormats.Center);
            XPen pen = new XPen(XColors.Navy, .5);

            gfx.DrawLine(pen, 70, 365, 520, 365);
            gfx.DrawString("Cité Hchachna en face CEM 1272 - Batna.", fonta, XBrushes.Black, new XRect(-135, 165, page.Width, page.Height), XStringFormats.Center);
            gfx.DrawString("Fixe : 033 28 30 67. Mobile : 0655 16 09 34", fonta, XBrushes.Black, new XRect(135, 165, page.Width, page.Height), XStringFormats.Center);
            XImage       image = XImage.FromFile(@"face.png");
            XImage       imagea = XImage.FromFile(@"twitter.png");
            XImage       imageb = XImage.FromFile(@"insta.png");
            XImage       imagec = XImage.FromFile(@"google.png");
            XImage       imaged = XImage.FromFile(@"link.png");
            const double dx = 500, dy = 790, dxa = 550, dxb = 600, dxc = 650, dxd = 700;

            double width = image.PixelWidth * 4.5 / image.HorizontalResolution;

            double height = image.PixelHeight * 4.5 / image.HorizontalResolution;

            gfx.DrawImage(image, (dx - width) / 2, (dy - height) / 2, width, height);
            gfx.DrawImage(imagea, (dxa - width) / 2, (dy - height) / 2, width, height);
            gfx.DrawImage(imageb, (dxb - width) / 2, (dy - height) / 2, width, height);
            gfx.DrawImage(imagec, (dxc - width) / 2, (dy - height) / 2, width, height);
            gfx.DrawImage(imaged, (dxd - width) / 2, (dy - height) / 2, width, height);

            // Save the document...
            FillExcelYear(nom, prenom, niveau, username);

            // Process open file dialog box results
            string mira  = i + "spec.pdf";
            string petha = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Printex");

            document.Save(System.IO.Path.Combine(petha, mira));
            // ...and start a viewer.
            //Process.Start(mira);
            var prima = new Imprimir();

            prima.Viewer.Navigate(System.IO.Path.Combine(petha, mira));
            prima.Show();
        }
Example #53
0
        private void Button(object sender, RoutedEventArgs e)
        {
            ChartLayer1.Width = 350;
            // Create a new PDF document
            var document = new PdfDocument();
            // Create an empty page
            var page = document.AddPage();
            // Get an XGraphics object for drawing
            var gfx     = XGraphics.FromPdfPage(page);
            var options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
            // Create a font
            var font = new XFont("Verdana", 16, XFontStyle.BoldItalic, options);

            // Draw the text
            gfx.DrawString(@"Состояние дорожного покрытия", font, XBrushes.Black,
                           new XRect(0, 20, page.Width, page.Height),
                           XStringFormats.TopCenter);

            var fonttext = new XFont("Times New Roman", 14, XFontStyle.Regular, options);

            gfx.DrawString("Название дороги:", fonttext, XBrushes.Black,
                           new XRect(30, 60, page.Width, page.Height),
                           XStringFormats.TopLeft);
            gfx.DrawString(Info.RoadName, fonttext, XBrushes.Black,
                           new XRect(230, 60, page.Width, page.Height),
                           XStringFormats.TopLeft);
            gfx.DrawString("Номер измерения:", fonttext, XBrushes.Black,
                           new XRect(30, 75, page.Width, page.Height),
                           XStringFormats.TopLeft);
            gfx.DrawString(Info.NumMess.ToString(), fonttext, XBrushes.Black,
                           new XRect(230, 75, page.Width, page.Height),
                           XStringFormats.TopLeft);
            gfx.DrawString("Дата проведения измерения:", fonttext, XBrushes.Black,
                           new XRect(30, 90, page.Width, page.Height),
                           XStringFormats.TopLeft);
            gfx.DrawString(Info.TimeStart, fonttext, XBrushes.Black,
                           new XRect(230, 90, page.Width, page.Height),
                           XStringFormats.TopLeft);
            gfx.DrawString("Общая протяженность участка:", fonttext, XBrushes.Black,
                           new XRect(30, 105, page.Width, page.Height),
                           XStringFormats.TopLeft);
            //gfx.DrawLine(XPens.Black, 0, 120, page.Width, 120);
            gfx.DrawString(Distance + " м", fonttext, XBrushes.Black,
                           new XRect(230, 105, page.Width, page.Height),
                           XStringFormats.TopLeft);



            //var sPdfFileName = Path.GetTempPath() + "PDFFile.pdf";

            var imageAll   = Path.GetTempPath() + "allgraf.png";
            var imageGen   = Path.GetTempPath() + "general.png";
            var imageLay1  = Path.GetTempPath() + "layer1.png";
            var imageLay2  = Path.GetTempPath() + "layer2.png";
            var imageLay3  = Path.GetTempPath() + "layer3.png";
            var imagePlotn = Path.GetTempPath() + "density.png";
            var imageCount = Path.GetTempPath() + "count.png";

            //Вызываем метод, чтобы сохранить график
            SaveAsPng(GetImage(GridAll), imageAll);
            SaveAsPng(GetImage(GridGen), imageGen);
            SaveAsPng(GetImage(GridLay1), imageLay1);
            SaveAsPng(GetImage(GridLay2), imageLay2);
            SaveAsPng(GetImage(GridLay3), imageLay3);
            SaveAsPng(GetImage(GridPlotn), imagePlotn);
            SaveAsPng(GetImage(GridCount), imageCount);

            //CreatePdfFromImage(sImagePath, sPdfFileName);



            var form = new XForm(document, XUnit.FromMillimeter(1500), XUnit.FromMillimeter(1600));
            // Create an XGraphics object for drawing the contents of the form.
            var formGfx = XGraphics.FromForm(form);

            // Draw a large transparent rectangle to visualize the area the form occupies
            //var back = XColors.Orange;
            //var brush = new XSolidBrush(back);
            //formGfx.DrawRectangle(brush, -300, -300, 300, 300);
            //var state = formGfx.Save();
            formGfx.DrawImage(XImage.FromFile(imageGen), 180, -4);
            formGfx.DrawImage(XImage.FromFile(imageCount), 35, 170);
            formGfx.DrawImage(XImage.FromFile(imageAll), 350, 170);
            formGfx.DrawImage(XImage.FromFile(imageLay3), 35, 390);
            formGfx.DrawImage(XImage.FromFile(imageLay2), 350, 390);
            formGfx.DrawImage(XImage.FromFile(imageLay1), 35, 600);
            formGfx.DrawImage(XImage.FromFile(imagePlotn), 350, 600);

            //formGfx.Restore(state);
            formGfx.Dispose();
            // Draw the form on the page of the document in its original size
            gfx.DrawImage(form, 10, 130, 3600, 3800);



            //DrawImage(gfx, sImagePath, 50, 50, 250, 250);

            // Show save file dialog box
            var dlg = new SaveFileDialog
            {
                FileName   = "Report",
                DefaultExt = ".text",
                Filter     = "Text documents (.pdf)|*.pdf"
            };
            var result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                var filename1 = dlg.FileName;
                using (var stm = File.Create(filename1))
                {
                    document.Save(stm);
                }
                Process.Start(filename1);
            }
        }
Example #54
0
        static void split_01(string file)
        {
            var db = RedisWrite.Db;
            // Open the file
            var    inputDoc = PdfSharp_IO.PdfReader.Open(file, PdfSharp_IO.PdfDocumentOpenMode.Import);
            long   fileSize = inputDoc.FileSize;
            int    max      = inputDoc.PageCount;
            string key      = DocumentStatic.buildId(max, fileSize);

            string name = Path.GetFileNameWithoutExtension(file);
            //if (max > 5) max = 5;


            var obj = new Dictionary <string, object>()
            {
                { "id", long.Parse(key) },
                { "file_name", Path.GetFileNameWithoutExtension(file) },
                { "file_type", "pdf" },
                { "file_size", fileSize },
                { "file_created", "" },
                { "page", max }
            };

            string jsonInfo = JsonConvert.SerializeObject(obj);
            var    bufInfo  = ASCIIEncoding.UTF8.GetBytes(jsonInfo);
            var    lsEntry  = new List <NameValueEntry>()
            {
                new NameValueEntry("0", LZ4Codec.Wrap(bufInfo, 0, bufInfo.Length))
            };

            db.HashSet("IDS", key, jsonInfo);

            for (int idx = 0; idx < max; idx++)
            {
                using (var outputDocument = new PdfSharp_.PdfDocument())
                {
                    var options = outputDocument.Options;
                    options.FlateEncodeMode = PdfSharp_.PdfFlateEncodeMode.BestCompression;
                    options.UseFlateDecoderForJpegImages = PdfSharp_.PdfUseFlateDecoderForJpegImages.Automatic;
                    options.CompressContentStreams       = true;
                    options.NoCompression   = false;
                    options.FlateEncodeMode = PdfSharp_.PdfFlateEncodeMode.BestCompression;

                    outputDocument.AddPage(inputDoc.Pages[idx]);

                    using (var ms = new MemoryStream())
                    {
                        outputDocument.Save(ms);
                        var bt = ms.ToArray();
                        int i  = idx + 1;
                        //outputDocument.Save(@"C:\temp\" + i + "-.pdf");
                        lsEntry.Add(new NameValueEntry(i.ToString(), LZ4Codec.Wrap(bt, 0, bt.Length)));
                        Console.WriteLine("{0}-{1}...", i, max);
                    }

                    //// Create new document
                    //var outputDocument = new PdfSharp_.PdfDocument();
                    //outputDocument.Version = inputDocument.Version;
                    //outputDocument.Info.Title = String.Format("Page {0} of {1}", i, inputDocument.Info.Title);
                    //outputDocument.Info.Creator = inputDocument.Info.Creator;

                    //// Add the page and save it
                    //outputDocument.AddPage(inputDocument.Pages[idx]);
                    //outputDocument.Save(@"C:\temp\" + i + "-.pdf");
                    //m_app.RedisUpdate(key, i.ToString(), ms.ToArray());
                }
            }
            ////long kkk = db.StreamDelete("BUF", new RedisValue[] { key + "-0" });
            string did = db.StreamAdd("RAW", lsEntry.ToArray(), key + "-0");
        }
        //Method used to merge 2 pdfs together
        public static void combinePDF(string targetPath, string[] pdfs, int pdfWithWaterMark, int pdfWithOutWaterMark, String pdfPrintOrder)
        {
            Boolean exceptionThrown  = true;
            Boolean addLogoException = true;

            PdfSharp.Pdf.PdfDocument one = null;
            PdfSharp.Pdf.PdfDocument two = null;
            //Messages.showGeneratingPDF();



            int counter = 0;

            while (addLogoException) //try to add the watermark
            {
                try
                {
                    AddLogo(pdfs[pdfWithWaterMark], pdfs[pdfWithWaterMark]); //pass to create water mark on the panel pdf
                    addLogoException = false;
                }
                catch (Exception e)
                {
                    addLogoException = true;
                    counter         += 1;
                    if (counter >= 10)
                    {
                        addLogoException = false;
                        System.Windows.Forms.MessageBox.Show("Error adding watermark: " + e.Message);
                    }
                }
            }
            while (exceptionThrown) //try to import the documents
            {
                try
                {
                    one             = PdfSharp.Pdf.IO.PdfReader.Open(pdfs[pdfWithWaterMark], PdfDocumentOpenMode.Import);
                    two             = PdfSharp.Pdf.IO.PdfReader.Open(pdfs[pdfWithOutWaterMark], PdfDocumentOpenMode.Import);
                    exceptionThrown = false;
                }
                catch (Exception e)
                {
                    exceptionThrown = false;
                    System.Windows.Forms.MessageBox.Show("Error printing PDF document." + e.Message);
                }
            }
            PdfSharp.Pdf.PdfDocument outPdf = new PdfSharp.Pdf.PdfDocument();
            if (pdfPrintOrder.Equals("Watermark Only")) //If the user only wants to add the water mark only rather than combining 2 PDFS
            {
                CopyPages(one, outPdf);
            }
            if (pdfPrintOrder.Equals("Drawings First"))  // If the user wants to draw the drawing first and then the agreement page or tool hit page
            {
                CopyPages(one, outPdf);                  //copy the content of pdf one in to new pdf
                CopyPages(two, outPdf);                  //copy the content of pdf two in to the new pdf (merging)
            }
            if (pdfPrintOrder.Equals("Drawings Second")) // If the user wants to draw the drawings second after the agreement page or tool hit page
            {
                CopyPages(two, outPdf);                  //copy the content of pdf two in to the new pdf
                CopyPages(one, outPdf);                  //copy the content of pdf one in to new pdf (merging)
            }
            File.Delete(pdfs[pdfWithWaterMark]);         //delete pdf one

            /*if (Messages.showCompressionRequired())
             * {
             * //File.Delete(targetPath); //delete the original file
             * CompressMyPdf(outPdf, targetPath);
             *
             * // outPdf.Save(targetPath);
             * RhinoApp.WriteLine("Compression Successful. Approval Drawing Completed");
             * }
             * else
             * {*/
            File.Delete(targetPath); //delete the original file
            outPdf.Save(targetPath);
            RhinoApp.WriteLine("PDF Successfully Saved. Approval Drawing Completed");
            //  }

            //Method combines the 2 pdf by copying all pages to a new pdf file
            void CopyPages(PdfSharp.Pdf.PdfDocument from, PdfSharp.Pdf.PdfDocument to) //inner method
            {
                for (int i = 0; i < from.PageCount; i++)
                {
                    to.AddPage(from.Pages[i]);
                }
            }
        }
Example #56
0
        private async void button2_Click(object sender, EventArgs e)
        {
            client = new FireSharp.FirebaseClient(config);
            if (!nameBox.Text.Equals(null) || !unameBox.Text.Equals(null) || !passBox1.Text.Equals(null) || !passBox2.Text.Equals(null) || !hstudyBox.Text.Equals(null) || !desigBox.Text.Equals(null) || !phnBox.Text.Equals(null) || !mailBox.Text.Equals(null) || !idBox.Text.Equals(null) || deptCBox.SelectedIndex == -1 || sessionBox.SelectedIndex == -1 || pictureBox1.Image == null)
            {
                if (passBox1.Text.Equals(passBox2.Text))
                {
                    StudentData d = new StudentData();
                    d.id   = hstudyBox.Text;
                    d.pass = passBox1.Text;
                    SetResponse res = null;
                    if (uType.Equals("Student"))
                    {
                        res = await client.SetTaskAsync("Student" + "Login/" + sessionBox.SelectedItem.ToString() + "/" + ch3 + unameBox.Text, d);
                    }
                    else if (uType.Equals("Alumni"))
                    {
                        AlumniData d1 = new AlumniData();
                        d1.name     = nameBox.Text;
                        d1.id       = idBox.Text;
                        d1.pass     = passBox1.Text;
                        d1.hStudy   = hstudyBox.Text;
                        d1.desig    = desigBox.Text;
                        d1.pAddrees = paddressBox.Text;
                        d1.phn      = phnBox.Text;
                        d1.mailid   = mailBox.Text;

                        String picSource = "D://3-1//Project c#//StudentTeacher//picSource//" + unameBox.Text + sessionBox.SelectedItem.ToString() + ".jpg";
                        d1.picid = picSource;
                        res      = await client.SetTaskAsync("AlumniLogin/" + ch3 + "/" + sessionBox.SelectedItem.ToString() + "/" + unameBox.Text, d1);


                        File.Delete(picSource);
                        //MessageBox.Show(imgLoc + "  " + picSource);
                        System.IO.File.Copy(imgLoc, picSource);

                        //MessageBox.Show(imgLoc+"  "+picSource);



                        String text = "\nName: " + nameBox.Text + "\nId: " + idBox.Text + "\nHigher Study Info: " + hstudyBox.Text + "\nDesignation: " + desigBox.Text + "\nPressent Address: " + paddressBox.Text + "\nContact No.: " + phnBox.Text + "\nEmai: " + mailBox.Text + "\nDepartment: " + deptCBox.SelectedItem.ToString() + "\nSession: " + sessionBox.SelectedItem.ToString();
                        PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();
                        PdfSharp.Pdf.PdfPage     page     = document.AddPage();
                        XGraphics gfx  = XGraphics.FromPdfPage(page);
                        XFont     font = new XFont("Times New Roman", 10, XFontStyle.Bold);
                        PdfSharp.Drawing.Layout.XTextFormatter tf = new PdfSharp.Drawing.Layout.XTextFormatter(gfx);

                        XRect rect = new XRect(40, 100, 250, 220);
                        gfx.DrawRectangle(XBrushes.SeaShell, rect);
                        tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft);


                        string pdfFilename = "D://3-1//Project c#//StudentTeacher//pdfSource//" + sessionBox.SelectedItem.ToString() + unameBox.Text + ".pdf";
                        document.Save(pdfFilename);
                        Process.Start(pdfFilename);



                        if (d1.pass.Equals(passBox1.Text))
                        {
                            MessageBox.Show("Registration Successfull..");
                            this.Hide();
                        }
                    }

                    else if (uType.Equals("Teacher"))
                    {
                        res = await client.SetTaskAsync(uType + "Login/" + unameBox.Text, d);
                    }
                }
                else
                {
                    MessageBox.Show("Passwords Are Not Identical..");
                }
            }
            else
            {
                MessageBox.Show("Some Fields are Not yet Filled or Selected....");
            }
        }
Example #57
0
        public byte[] RenderToBytes(string title    = null, string author = null, string subject = null,
                                    string keywords = null)
        {
            // 1. For all PDF documents render pages with no header or footer, but with the correct header and footer heights.
            // The final output document
            var finalPdf = new PdfSharp.Pdf.PdfDocument();

            finalPdf.Info.Title    = title;
            finalPdf.Info.Author   = author;
            finalPdf.Info.Subject  = subject;
            finalPdf.Info.Keywords = keywords;
            finalPdf.Info.Creator  = "ItechoPDF";

            var pageCounters = DocumentToPdf(finalPdf);

            // Now generate headers and footers
            foreach (var doc in Documents)
            {
                // get all pages of the generated document
                var counters = pageCounters
                               .Where(c => c.RenderDocument == doc)
                               .ToList();

                // and generate a header / footer pair for each page
                // one page can be rendered as multiple pages
                var html = BuildHeaderFooter(doc, counters);

                if (html == null)
                {
                    continue;
                }
                // add 1mm extra to fill rounding height issues caused by WkhtmlToPdf
                var height = Math.Max(doc.HeaderHeight, doc.FooterHeight) + 1;
                // Keep the same settings as the document except the height and y - margins
                var settings = ConvertToCoreSettings(doc);
                // JSDelay and windows status in headers and footer not supported yet.
                settings.JSDelay      = 0;
                settings.WindowStatus = null;

                settings.Orientation = Orientation.Portrait;
                if (doc.Settings.Orientation == Orientation.Landscape)
                {
                    settings.PaperHeight = height + "mm";
                    settings.PaperWidth  = doc.Settings.PaperSize.Height + "mm";
                }
                else
                {
                    settings.PaperHeight = height + "mm";
                    settings.PaperWidth  = doc.Settings.PaperSize.Width + "mm";
                }

                settings.MarginBottom = "0mm";
                settings.MarginTop    = "0mm";

                var bytes = HtmlToPdf(html, settings);

                XPdfForm hf = XPdfForm.FromStream(new MemoryStream(bytes));

                // HF can be 1 page more than pages because of page breaks or of manual page breaking inside headers or footers
                // But should never be less.
                if (hf.PageCount < counters.Count() * 2)
                {
                    throw new Exception("Header and footer segments does not match number of pages.");
                }

                int pageCount = 0;
                foreach (var c in counters)
                {
                    XGraphics gfx = XGraphics.FromPdfPage(c.PdfPage);
                    // 1 inch = 72 points, 1 inch = 25.4 mm, 1 point = 0.352777778 mm
                    // points per millimeter
                    var ppm = c.PdfPage.Height.Point /
                              c.PdfPage.Height.Millimeter; // or page.Width.Point / page.Width.Millimeter
                    var mt = doc.Settings.Margins.Top ?? 0;
                    var mb = doc.Settings.Margins.Bottom ?? 0;

                    hf.PageIndex = pageCount++;
                    gfx.DrawImage(hf, 0, mt * ppm);

                    hf.PageIndex = pageCount++;
                    gfx.DrawImage(hf, 0, c.PdfPage.Height - ((doc.FooterHeight - mb) * ppm));
                }
            }

            using (var ms = new MemoryStream())
            {
                finalPdf.Save(ms);
                return(ms.ToArray());
            }
        }
Example #58
0
        private void button1_Click(object sender, EventArgs e)
        {
            string SelectedBook = File.ReadAllText(@"C:/Temp/SelectedBook.txt");
            int    FileCount    = Directory.GetFiles(@"C:/Temp/fixed/").Length;
            int    i            = 0;
            int    filename     = 001;


            progressBar1.Maximum = FileCount * 2;
            progressBar1.Minimum = 1;
            progressBar1.Visible = true;
            progressBar1.Step    = 1;


            while (i != FileCount)
            {
                string filepath   = File.ReadAllText(@"C:/Temp/fixed/fixed" + i + ".html");
                string exportpath = "C:/Temp/pdf/" + filename.ToString("0000") + ".pdf";
                NReco.PdfGenerator.HtmlToPdfConverter pdfConverter = new NReco.PdfGenerator.HtmlToPdfConverter();
                pdfConverter.PageWidth  = 5000;
                pdfConverter.PageHeight = 5000;
                pdfConverter.Margins    = new NReco.PdfGenerator.PageMargins {
                    Top = 0, Bottom = 0, Left = 0, Right = 0
                };
                pdfConverter.CustomWkHtmlArgs = "  --dpi 300 --disable-smart-shrinking";
                byte[] pdfBuffer = pdfConverter.GeneratePdf(filepath);
                File.WriteAllBytes(exportpath, pdfBuffer);
                i++;
                filename++;
                progressBar1.PerformStep();
            }


            int PDFCount = Directory.GetFiles(@"C:/Temp/pdf/").Length;



            //Beide XPoints sollten stimmen
            //XSize1 = width
            //XSize2 = height
            int XPoint1  = 0;
            int XPoint2  = 14173;
            int XSize1   = 0;
            int XSize2   = 0;
            int PdfCount = Directory.GetFiles(@"C:/Temp/pdf/").Length;

            if (SelectedBook == "NA")
            {
                XSize1 = 329;
                XSize2 = 447;
            }
            else if (SelectedBook == "RM")
            {
                XSize1 = 100;
                XSize2 = 400;
            }
            else if (SelectedBook == "FM")
            {
                XSize1 = 361;
                XSize2 = 510;
            }
            else if (SelectedBook == "MW")
            {
                XSize1 = 446;
                XSize2 = 631;
            }
            else if (SelectedBook == "TD")
            {
                XSize1 = 446;
                XSize2 = 631;
            }
            else if (SelectedBook == "CUSTOM")
            {
                string[] lines = File.ReadAllLines(@"C:/Temp/custom/custom.txt");


                int width  = Int16.Parse(lines[3]);
                int height = Int16.Parse(lines[4]);
                if (lines[0] == "mm")
                {
                    XSize1 = Convert.ToInt32(width * 2.8346456693);
                    XSize2 = Convert.ToInt32(height * 2.8346456693);
                }
                else if (lines[0] == "px")
                {
                    XSize1 = Convert.ToInt32(width * 0.75);
                    XSize2 = Convert.ToInt32(height * 0.75);
                }
            }



            XPoint2 = XPoint2 - XSize2;
            int x         = 1;
            int FileName2 = 1;

            while (x < PdfCount + 1)
            {
                string      file     = @"C:/Temp/pdf/" + FileName2.ToString("0000") + ".pdf";
                PdfDocument document = PdfReader.Open(file);
                PdfPage     page     = document.Pages[0];
                page.CropBox = new PdfRectangle(new XPoint(XPoint1, XPoint2),
                                                new XSize(XSize1, XSize2));
                document.Save(file);
                x++;
                FileName2++;
                progressBar1.PerformStep();
            }



            string FileName = File.ReadAllText(@"C:/Temp/SelectedBook.txt");

            string[] pdfs = Directory.GetFiles(@"C:/Temp/pdf/", "*.pdf*", SearchOption.AllDirectories);

            string targetPath = @"C:/Temp/" + FileName + ".pdf";

            using (var targetDoc = new PdfSharp.Pdf.PdfDocument())
            {
                foreach (var pdf in pdfs)
                {
                    using (var pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(pdf, PdfDocumentOpenMode.Import))
                    {
                        for (var y = 0; y < pdfDoc.PageCount; y++)
                        {
                            targetDoc.AddPage(pdfDoc.Pages[y]);
                        }
                    }
                }
                targetDoc.Save(targetPath);
            }
            Process.Start(@"C:/Temp/" + FileName + ".pdf");
            MessageBox.Show("Die Umwandlung ist abgeschlossen, du kannst nun fortfahren.", "Umwandlung Abgeschlossen", MessageBoxButtons.OK);
        }
Example #59
0
        private void CreerPDF_Click(object sender, EventArgs e)
        {
            PdfDocument doc = new PdfDocument();

            doc.Info.Title = "Created with PDFsharp";


            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();
            XGraphics   gfx      = XGraphics.FromPdfPage(page);
            XFont       font     = new XFont("Times New Roman", 8, XFontStyle.Bold);
            XPen        pen      = new XPen(XColors.Black, 0.8);

            gfx.DrawRectangle(pen, 75, 70, 150, 65);
            gfx.DrawRectangle(pen, 400, 70, 125, 65);

            gfx.DrawString("Lycée Pasteur Mont Roland", font, XBrushes.Black, 100, 80);
            gfx.DrawString("Enseignement Supérieur", font, XBrushes.Black, 107, 90);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawString("9 avenue Rockefeller", font, XBrushes.Black, 117, 100);
            gfx.DrawString("BP 24", font, XBrushes.Black, 139, 110);
            gfx.DrawString("39107 Dole Cedex", font, XBrushes.Black, 120, 120);
            gfx.DrawString("03 84 79 75 00", font, XBrushes.Black, 127, 130);
            gfx.DrawString("En partenariat avec :", font, XBrushes.Black, 429, 80);
            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("CFA ASPECT", font, XBrushes.Black, 438, 100);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawString("20 rue Megevand", font, XBrushes.Black, 435, 110);
            gfx.DrawString("25041 Besançon", font, XBrushes.Black, 436, 120);
            gfx.DrawString("03 81 25 03 75", font, XBrushes.Black, 439, 130);
            gfx.DrawImage(XImage.FromFile("lpmr.png"), 230, 75, 80, 50);
            gfx.DrawImage(XImage.FromFile("aspect.jpg"), 318, 75, 80, 50);
            font = new XFont("Times New Roman", 10, XFontStyle.Bold);
            gfx.DrawString("RELEVE DE NOTES - Promotion 2019 2021 - Première année", font, XBrushes.Black, 184, 160);
            gfx.DrawString("Administrateur de Systèmes d'Information", font, XBrushes.Black, 222, 180);
            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("TITRE RNCP de Niveau 6 - N° de certification 26E32601 - Code NSF 326 n", font, XBrushes.Black, 186, 195);

            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawString("Nom de l'apprenti : DIZIERE Emma", font, XBrushes.Black, 90, 220);
            pen = new XPen(XColors.Black, 1);
            XBrush brush = new XSolidBrush(XColor.FromArgb(240, 240, 240));

            gfx.DrawRectangle(pen, brush, 75, 225, 450, 15);
            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("Envaluation au sein du centre de formation ", font, XBrushes.Black, 228, 235);
            pen  = new XPen(XColors.Black, 0.8);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawRectangle(pen, 75, 240, 80, 20);

            gfx.DrawString("Matières ", font, XBrushes.Black, 100, 252);

            gfx.DrawRectangle(pen, 155, 240, 180, 10);
            gfx.DrawRectangle(pen, 155, 260, 180, 10);
            gfx.DrawRectangle(pen, 155, 280, 180, 10);

            gfx.DrawString("Moyennes sur 20", font, XBrushes.Black, 222, 248);
            gfx.DrawRectangle(pen, 155, 250, 36, 10);

            gfx.DrawString("Coef", font, XBrushes.Black, 164, 258);
            gfx.DrawRectangle(pen, 191, 250, 36, 10);
            gfx.DrawString("Ctrl Cont", font, XBrushes.Black, 194, 258);
            gfx.DrawRectangle(pen, 227, 250, 36, 10);
            gfx.DrawString("Examen", font, XBrushes.Black, 232, 258);
            gfx.DrawRectangle(pen, 263, 250, 36, 10);
            gfx.DrawString("Total", font, XBrushes.Black, 272, 258);
            gfx.DrawRectangle(pen, 299, 250, 36, 10);
            gfx.DrawString("Classe", font, XBrushes.Black, 307, 258);
            gfx.DrawRectangle(pen, 335, 240, 190, 20);
            gfx.DrawString("Notes sur 20", font, XBrushes.Black, 414, 252);

            gfx.DrawString("6", font, XBrushes.Black, 164, 268);
            gfx.DrawRectangle(pen, 155, 260, 180, 10);
            gfx.DrawRectangle(pen, 155, 260, 36, 10);
            gfx.DrawRectangle(pen, 227, 260, 36, 10);
            gfx.DrawRectangle(pen, 263, 260, 36, 10);
            gfx.DrawString("Soutenance Orale ", font, XBrushes.Black, 80, 268);
            gfx.DrawRectangle(pen, 75, 260, 450, 10);

            gfx.DrawString("3", font, XBrushes.Black, 164, 278);
            gfx.DrawRectangle(pen, 155, 270, 180, 10);
            gfx.DrawRectangle(pen, 155, 270, 36, 10);
            gfx.DrawRectangle(pen, 227, 270, 36, 10);
            gfx.DrawRectangle(pen, 263, 270, 36, 10);
            gfx.DrawString("Projet Pédagogique ", font, XBrushes.Black, 80, 278);
            gfx.DrawRectangle(pen, 75, 270, 450, 10);

            gfx.DrawString("6", font, XBrushes.Black, 164, 288);
            gfx.DrawRectangle(pen, 155, 280, 180, 10);
            gfx.DrawRectangle(pen, 155, 280, 36, 10);
            gfx.DrawRectangle(pen, 227, 280, 36, 10);
            gfx.DrawRectangle(pen, 263, 280, 36, 10);
            gfx.DrawString("Evaluation Entreprise ", font, XBrushes.Black, 80, 288);
            gfx.DrawRectangle(pen, 75, 280, 450, 10);


            gfx.DrawString("Moyenne", font, XBrushes.Black, 164, 298);
            gfx.DrawRectangle(pen, 75, 290, 450, 10);
            gfx.DrawRectangle(pen, 263, 290, 36, 10);
            gfx.DrawRectangle(pen, 299, 290, 36, 10);
            gfx.DrawRectangle(pen, 335, 290, 190, 10);

            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("Evaluation en entreprise", font, XBrushes.Black, 228, 318);
            pen  = new XPen(XColors.Black, 0.8);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawRectangle(pen, 75, 310, 450, 10);
            gfx.DrawString("Projet Entreprise", font, XBrushes.Black, 164, 328);
            gfx.DrawRectangle(pen, 75, 320, 450, 10);
            gfx.DrawRectangle(pen, 263, 320, 36, 10);
            gfx.DrawRectangle(pen, 299, 320, 36, 10);
            gfx.DrawRectangle(pen, 335, 320, 190, 10);

            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("Appréciation du conseil de promotion et du responsable de dispositif", font, XBrushes.Black, 198, 348);
            pen  = new XPen(XColors.Black, 0.8);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawRectangle(pen, 75, 340, 450, 10);
            gfx.DrawRectangle(pen, 75, 350, 450, 100);


            gfx.DrawString("Rappel Moyenne année 1", font, XBrushes.Black, 134, 368);
            gfx.DrawString("Rappel Moyenne année 2 semestre 1", font, XBrushes.Black, 134, 378);
            gfx.DrawString("Moyenne Certification", font, XBrushes.Black, 134, 388);
            gfx.DrawString("Total", font, XBrushes.Black, 134, 398);

            gfx.DrawRectangle(pen, 284, 360, 30, 10);
            gfx.DrawRectangle(pen, 284, 370, 30, 10);
            gfx.DrawRectangle(pen, 284, 380, 30, 10);
            gfx.DrawRectangle(pen, 284, 390, 30, 10);

            gfx.DrawString("A Dole le 10 mars 2021 ", font, XBrushes.Black, 290, 408);
            gfx.DrawString("Le responsable de dispositif : Julian COURBEZ", font, XBrushes.Black, 290, 418);


            const string filename = "Bulletin-notes-final.pdf";

            document.Save(filename);

            Process.Start(filename);
        }
Example #60
-1
    public void TestExternalXpsFiles()
    {
      string path = "PdfSharp/testing/SampleXpsDocuments_1_0/";
      string dir = GetDirectory(path);
      if (dir == null)
        throw new FileNotFoundException("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");
      if (!Directory.Exists(dir))
        throw new FileNotFoundException("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");

      string[] files = Directory.GetFiles(dir, "*.xps", SearchOption.AllDirectories);
      
      if (files.Length == 0)
        throw new Exception("No sample file found. Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");

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

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

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

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

            pdfDoc.Save(pdfFilename);
            docIndex++;
          }
        }
        catch (Exception ex)
        {
          Debug.WriteLine(ex.Message);
          GetType();
        }
      }
    }