Ejemplo n.º 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);
    }
Ejemplo n.º 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));
      }
    }
Ejemplo n.º 3
2
        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;
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 5
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);
    }
Ejemplo n.º 6
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);
 }
Ejemplo n.º 7
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.");
                }
            }
        }
Ejemplo n.º 8
0
 void CreatePage()
 {
     Page             = _document.AddPage();
     Page.Size        = PageSize.A4;
     Gfx              = XGraphics.FromPdfPage(Page);
     _currentPosition = _topPosition;
 }
 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;
     }
 }
Ejemplo n.º 10
0
 public static void CreatePdf(Sheet sheet,string fullFileName)
 {
     PdfDocument document=new PdfDocument();
     PdfPage page=document.AddPage();
     CreatePdfPage(sheet,page);
     document.Save(fullFileName);
 }
Ejemplo n.º 11
0
        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();
            }
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
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));
            }
        }
Ejemplo n.º 14
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");
                }
            }
        }
Ejemplo n.º 15
0
Archivo: Form1.cs Proyecto: 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);
            }
        }
Ejemplo n.º 16
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");
                }
            }
        }
Ejemplo n.º 17
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");                          //경로가 절대 주소여서 바꿔줘야 합니다.
                }
            }
        }
Ejemplo n.º 18
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";
        }
Ejemplo n.º 19
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);
        }
    }
Ejemplo n.º 20
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();
            }
        }
        // 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);
            }
        }
Ejemplo n.º 22
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]);
     }
 }
Ejemplo n.º 23
0
 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 };
     }
     //////////////////////////////////////////////////////////////////////
 }
Ejemplo n.º 24
0
 public static XGraphics NewPage(PdfDocument document, XUnit width, XUnit height)
 {
     var page = document.AddPage();
     page.Width = width;
     page.Height = height;
     return XGraphics.FromPdfPage(page);
 }
Ejemplo n.º 25
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();
    }
Ejemplo n.º 26
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"));
    }
Ejemplo n.º 27
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);
    }
Ejemplo n.º 28
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");
        }
Ejemplo n.º 29
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;
        }
Ejemplo n.º 30
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);
    }
Ejemplo n.º 31
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);
                }
            }
        }
Ejemplo n.º 32
0
        static XGraphics AddPageTo(PdfDocument document, Unit width, Unit height)
        {
            PdfPage page = document.AddPage();
            page.Width = width.Points;
            page.Height = height.Points;

            return XGraphics.FromPdfPage(page);
        }
Ejemplo n.º 33
0
 static PdfPrintTarget()
 {
     m_doc = new PdfDocument();
     m_page = m_doc.AddPage();
     m_info = XGraphics.FromPdfPage(m_page);
     m_size = PageSizeConverter.ToSize(m_page.Size);
     m_mmkx = m_size.Width / 210.0f;
     m_mmky = m_size.Height / 297.0f;
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 35
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");
        }
Ejemplo n.º 36
0
    static void Main(string[] args)
    {
      string filename = "Graphics-G.pdf";
      filename = Guid.NewGuid().ToString("D").ToUpper() + ".pdf";
      document = new PdfDocument();
      document.Info.Title = "PDFsharp XGraphic Sample";
      document.Info.Author = "Stefan Lange";
      document.Info.Subject = "Created with code snippets that show the use of graphical functions";
      document.Info.Keywords = "PDFsharp, XGraphics";

      new LinesAndCurves().DrawPage(document.AddPage());
      new Shapes().DrawPage(document.AddPage());
      new Paths().DrawPage(document.AddPage());
      new Text().DrawPage(document.AddPage());
      new Images().DrawPage(document.AddPage());

      // Save the document...
      document.Save(filename);
      // ...and start a viewer
      Process.Start(filename);
    }
Ejemplo n.º 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;
 }
Ejemplo n.º 38
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));
        }
Ejemplo n.º 39
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");
 }
Ejemplo n.º 40
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);
                                                   }
                                         });
                }
            }
        }
Ejemplo n.º 41
0
    static void Main()
    {
      // Create a temporary file
      string filename = String.Format("{0}_tempfile.pdf", Guid.NewGuid().ToString("D").ToUpper());
      s_document = new PdfDocument();
      s_document.Info.Title = "PDFsharp XGraphic Sample";
      s_document.Info.Author = "Stefan Lange";
      s_document.Info.Subject = "Created with code snippets that show the use of graphical functions";
      s_document.Info.Keywords = "PDFsharp, XGraphics";

      // Create demonstration pages
      new LinesAndCurves().DrawPage(s_document.AddPage());
      new Shapes().DrawPage(s_document.AddPage());
      new Paths().DrawPage(s_document.AddPage());
      new Text().DrawPage(s_document.AddPage());
      new Images().DrawPage(s_document.AddPage());

      // Save the s_document...
      s_document.Save(filename);
      // ...and start a viewer
      Process.Start(filename);
    }
Ejemplo n.º 42
0
        public void DrawTest()
        {
            var rect = new XRect(0, 0, 10, 40);
            var alignment = new XParagraphAlignment(); 
            string content = "foo"; 
            var target = new Label(alignment, content){Rect = rect};
            PdfDocument pdf = new PdfDocument();
            var page = pdf.AddPage();
            XGraphics gfx = XGraphics.FromPdfPage(page);

            target.Draw(gfx);
            Assert.AreEqual(target.Rect, rect);
        }
Ejemplo n.º 43
0
 public static PdfDocument makePDF()
 {
     PdfDocument pdf = new PdfDocument();
     pdf.Info.Title = "My First PDF";
     PdfPage pdfPage = pdf.AddPage();
     XGraphics graph = XGraphics.FromPdfPage(pdfPage);
     XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
     graph.DrawString("This is my first PDF document", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.Center);
     string pdfFilename = "firstpage.pdf";
     pdf.Save(pdfFilename);
     Process.Start(pdfFilename);
     return pdf;
 }
Ejemplo n.º 44
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);
        }
Ejemplo n.º 45
0
 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);
     }
 }
Ejemplo n.º 46
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);
        }
Ejemplo n.º 47
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]);
        }
Ejemplo n.º 48
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);
        }
Ejemplo n.º 49
0
    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");
    }
Ejemplo n.º 50
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);
            }
        }
Ejemplo n.º 51
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);
        }
Ejemplo n.º 52
0
 /// <summary>
 /// Merges all the image pages into a new pdf page for the specified doc.
 /// </summary>
 /// <param name="doc">The document.</param>
 /// <param name="srcDoc">The source document.</param>
 /// <param name="newPageCallback">The callback after the image has been added as a new pdf page.</param>
 /// <param name="includePageCallback">The callback to check if a page should be included.</param>
 /// <exception cref="System.ArgumentNullException">doc</exception>
 public static void AddMultipage(this PdfDocument doc, PdfDocument srcDoc, Action <int, PdfPage> newPageCallback, Predicate <int> includePageCallback = null)
 {
     if (doc == null)
     {
         throw new ArgumentNullException("doc");
     }
     if (srcDoc != null)
     {
         var total = srcDoc.PageCount;
         for (int i = 0; i < total;)
         {
             i++;
             if (includePageCallback == null || includePageCallback(i))
             {
                 var newPg = doc.AddPage(srcDoc.Pages[i - 1]);
                 if (newPageCallback != null)
                 {
                     newPageCallback(i, newPg);
                 }
             }
         }
     }
 }
Ejemplo n.º 53
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();
        }
Ejemplo n.º 54
0
        // create a preview
        public void CreatePreview()
        {
            XRect rect;
            XPen  pen;

            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);
            double    x = 50, y = 100;
            XFont     fontH1 = new XFont("Times", 18, XFontStyle.Bold);

            XFont font = new XFont("Times", 12);

            XFont fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic);

            double ls = font.GetHeight(gfx);

            // Draw some text

            gfx.DrawString("Create PDF on the fly with PDFsharp", fontH1, XBrushes.Black, x, x);

            gfx.DrawString("With PDFsharp you can use the same code to draw graphic, " +
                           "text and images on different targets.", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("The object used for drawing is the XGraphics object.",
                           font, XBrushes.Black, x, y);
            y += 2 * ls;
            // Draw an arc

            pen = new XPen(XColors.Red, 4);

            pen.DashStyle = XDashStyle.Dash;

            gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120);

            // Draw a star
            XGraphicsState gs = gfx.Save();

            gfx.TranslateTransform(x + 140, y + 30);

            for (int idx = 0; idx < 360; idx += 10)

            {
                gfx.RotateTransform(10);

                gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0);
            }

            gfx.Restore(gs);

            // Draw a rounded rectangle
            rect = new XRect(x + 230, y, 100, 60);
            pen  = new XPen(XColors.DarkBlue, 2.5);
            XColor color1 = XColor.FromKnownColor(KnownColor.DarkBlue);
            XColor color2 = XColors.Red;
            XLinearGradientBrush lbrush = new XLinearGradientBrush(rect, color1, color2,
                                                                   XLinearGradientMode.Vertical);

            gfx.DrawRoundedRectangle(pen, lbrush, rect, new XSize(10, 10));

            // Draw a pie
            pen           = new XPen(XColors.DarkOrange, 1.5);
            pen.DashStyle = XDashStyle.Dot;
            gfx.DrawPie(pen, XBrushes.Blue, x + 360, y, 100, 60, -130, 135);

            // Draw some more text
            y += 60 + 2 * ls;
            gfx.DrawString("With XGraphics you can draw on a PDF page as well as on any System.Drawing.Graphics object.", font, XBrushes.Black, x, y);
            y += ls * 1.1;
            gfx.DrawString("Use the same code to", font, XBrushes.Black, x, y);
            x += 10;
            y += ls * 1.1;
            gfx.DrawString("• draw on a newly created PDF page", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw above or beneath of the content of an existing PDF page", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a window", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw on a printer", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a bitmap image", font, XBrushes.Black, x, y);
            x -= 10;
            y += ls * 1.1;
            gfx.DrawString("You can also import an existing PDF page and use it like an image, e.g. draw it on another PDF page.", font, XBrushes.Black, x, y);
            y += ls * 1.1 * 2;
            gfx.DrawString("Imported PDF pages are neither drawn nor printed; create a PDF file to see or print them!", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            gfx.DrawString("Below this text is a PDF form that will be visible when viewed or printed with a PDF viewer.", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            XGraphicsState state   = gfx.Save();
            XRect          rcImage = new XRect(100, y, 100, 100 * Math.Sqrt(2));

            gfx.DrawRectangle(XBrushes.Snow, rcImage);
            string kara = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Printex");

            gfx.DrawImage(XPdfForm.FromFile(System.IO.Path.Combine(kara, "slother.pdf")), rcImage);
            gfx.Restore(state);
        }
Ejemplo n.º 55
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);
        }
Ejemplo n.º 56
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);
            }
        }
Ejemplo n.º 57
0
        private List <PageCount> DocumentToPdf(PdfSharp.Pdf.PdfDocument finalPdf)
        {
            var pageCounters  = new List <PageCount>();
            int pageCount     = 0;
            int documentCount = 0;

            foreach (var doc in Documents)
            {
                // Concatenate all pages into one HTML document for performance
                // Try to minimize calls to native WkHtmlToPdf because it's slowish.
                var htmlPages = BuildHtml(doc);

                var settings = ConvertToCoreSettings(doc);
                var bytes    = HtmlToPdf(htmlPages, settings);

                // Now read / parse the generate PDF to determine page counts
                var pdf             = PdfReader.Open(new MemoryStream(bytes), PdfDocumentOpenMode.Import);
                var overflowCount   = 0;
                var renderPageIndex = 0;
                for (var p = 0; p < pdf.PageCount; p++)
                {
                    var page = pdf.Pages[p];
                    // DocumentSplit
                    if (IsPageSplit(page))
                    {
                        // Update the last overflow overflowCount to overflowCount
                        for (var i = 0; i < overflowCount; i++)
                        {
                            pageCounters[pageCounters.Count - i - 1].Overflows = overflowCount - 1;
                        }

                        overflowCount = 0;
                        renderPageIndex++;
                        continue;
                    }

                    var newPage = finalPdf.AddPage(page);

                    pageCounters.Add(new PageCount
                    {
                        Overflow = overflowCount,
                        Page     = pageCount,
                        Document = documentCount,
                        PdfPage  = newPage,

                        RenderDocument = doc,
                        RenderPage     = doc.Pages.ElementAt(renderPageIndex)
                    });

                    overflowCount++;
                    pageCount++;
                }

                documentCount++;
            }

            // Update document and page count
            foreach (var c in pageCounters)
            {
                c.Documents = documentCount - 1;
                c.Pages     = pageCount - 1;
            }

            return(pageCounters);
        }
Ejemplo n.º 58
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");
        }
Ejemplo n.º 59
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);
        }
Ejemplo n.º 60
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....");
            }
        }