private static string GeneratePlaceholderFile(string workingFolder, string fileName, string documentHandle)
        {
            string pdfFileToAppend = Path.Combine(workingFolder, Guid.NewGuid() + ".pdf");

            using (PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument())
            {
                // Create an empty page
                PdfSharp.Pdf.PdfPage page = document.AddPage();

                // Get an XGraphics object for drawing
                using (XGraphics gfx = XGraphics.FromPdfPage(page))
                {
                    // Create a font
                    XFont font = new XFont("Verdana", 14, XFontStyle.Bold);

                    // Draw the text
                    gfx.DrawString("Handle " + documentHandle + " fileName " + fileName + " has no pdf format",
                                   font,
                                   XBrushes.Black,
                                   new XRect(0, 0, page.Width, page.Height),
                                   XStringFormats.TopCenter);
                }

                document.Save(pdfFileToAppend);
            }

            return(pdfFileToAppend);
        }
Beispiel #2
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());
                    }
                }
            }
        }
Beispiel #3
0
        static void CropPdf2()
        {
            string fn = @"D:\username\Desktop\0001 Altstetten - GB01 H602 - OG14.pdf";

            int ten     = (int)(28.3465 * 10);
            int hundred = (int)(28.3465 * 100);

            int x = ten / 20;
            int y = hundred / 20;

            PdfSharp.Drawing.XRect cropDim = new PdfSharp.Drawing.XRect(0, 0, 200, 200);
            cropDim = new PdfSharp.Drawing.XRect(200, 200, 200, 200);

            using (PdfSharp.Pdf.PdfDocument sourceDocument = PdfSharp.Pdf.IO.PdfReader.Open(fn))
            {
                PdfSharp.Pdf.PdfPage sourcePage = sourceDocument.Pages[0];

                // Crop the PDF - DOES IT WRONG...
                // sourcePage.CropBox = new PdfSharp.Pdf.PdfRectangle(cropDim);

                PdfSharp.Drawing.XRect cropRect = new PdfSharp.Drawing.XRect(cropDim.X, sourcePage.Height.Point - cropDim.Height - cropDim.Y, cropDim.Width, cropDim.Height);
                sourcePage.CropBox = new PdfSharp.Pdf.PdfRectangle(cropRect);

                sourceDocument.Save("CropPdf2.pdf");
            } // End Using sourceDocument
        }     // End Sub CropPdf2
Beispiel #4
0
        public static void Main()
        {
            //Microsoft.Azure.Devices.Client a;              Microsoft.Azure.Devices.Client.DeviceAuthenticationWithX509Certificate
            // Create a new PDF document
            PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();

            // Create an empty page
            PdfSharp.Pdf.PdfPage page = document.AddPage();
        }
Beispiel #5
0
 private static void CombineMultiplePDFs(string[] args, string outFile)
 {
     PdfSharp.Pdf.PdfDocument pdfdocument = new PdfSharp.Pdf.PdfDocument();
     foreach (string str in args)
     {
         PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(str, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
         int count = inputDocument.PageCount;
         for (int idx = 0; idx < count; idx++)
         {
             PdfSharp.Pdf.PdfPage page = inputDocument.Pages[idx];
             pdfdocument.AddPage(page);
         }
     }
     pdfdocument.Save(outFile);
 }
Beispiel #6
0
        static void PdfSharpTestParseReference(PdfSharp.Pdf.Advanced.PdfReference reference)
        {
            if (reference == null)
            {
                return;
            }

            switch (reference.Value.GetType().ToString())
            {
            case "PdfSharp.Pdf.Advanced.PdfContent":

                PdfSharp.Pdf.Advanced.PdfContent pdfContent = reference.Value as PdfSharp.Pdf.Advanced.PdfContent;

                String content = System.Text.ASCIIEncoding.ASCII.GetString(pdfContent.Stream.Value);

                foreach (String currentCommand in content.Split('\n'))
                {
                    System.Diagnostics.Debug.WriteLine("Command: " + currentCommand);
                }

                break;

            case "PdfSharp.Pdf.PdfDictionary":

                PdfSharp.Pdf.PdfDictionary dictionary = reference.Value as PdfSharp.Pdf.PdfDictionary;

                PdfSharpTestParseDictionary(dictionary);

                break;

            case "PdfSharp.Pdf.PdfPage":

                PdfSharp.Pdf.PdfPage pdfPage = reference.Value as PdfSharp.Pdf.PdfPage;

                break;


            default:

                System.Diagnostics.Debug.WriteLine("[REFERENCE PARSE UNKNOWN TYPE] " + reference.Value.GetType().ToString());

                break;
            }

            return;
        }
Beispiel #7
0
        public List <Image> pdfToImage(string pdfFilePath, int dpi, float resModifier)
        {
            // Create a PDF converter instance by loading a local file
            PdfImageConverter pdfConverter = new PdfImageConverter(pdfFilePath);

            // Set the dpi, the output image will be rendered in such resolution
            pdfConverter.DPI = dpi;

            // the output image will be rendered to grayscale image or not
            pdfConverter.GrayscaleOutput = true;

            // open and load the file
            using (PdfSharp.Pdf.PdfDocument inputDocument = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import))
            {
                List <Image> tempImagePdfPages = new List <Image>();

                // process and save pages one by one
                for (int i = 0; i < inputDocument.Pages.Count; i++)
                {
                    PdfSharp.Pdf.PdfPage currentPage = inputDocument.Pages[i];

                    /*// Create instance of Ghostscript wrapper class.
                     * GS gs = new GS();*/

                    /*int widthPdfPage = Convert.ToInt32(currentPage.Width.Point);
                     * int heightPdfPage = Convert.ToInt32(currentPage.Height.Point);*/

                    int widthPdfPage  = Convert.ToInt32(currentPage.Width.Point * resModifier);
                    int heightPdfPage = Convert.ToInt32(currentPage.Height.Point * resModifier);

                    // Convert pdf to png in customized image size
                    Image image = pdfConverter.PageToImage(i, widthPdfPage, heightPdfPage);

                    tempImagePdfPages.Add(image);
                }

                pdfConverter.Dispose();

                return(tempImagePdfPages);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Paint the report
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            PdfSharp.Pdf.PdfDocument   document = new PdfSharp.Pdf.PdfDocument();
            PdfSharp.Drawing.XGraphics xg;

            Graphics g2D     = e.Graphics;
            Bitmap   drawing = null;

            drawing = new Bitmap(this.Width, this.Height, e.Graphics);
            g2D     = Graphics.FromImage(drawing);
            g2D.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
            RectangleF bounds = g2D.VisibleClipBounds;
            SolidBrush brush  = new SolidBrush(COLOR_BACKGROUND);   //background color filling

            g2D.FillRectangle(brush, bounds.X, bounds.Y, bounds.Width, bounds.Height);
            for (int page = 0; page < m_layout.GetPages().Count(); page++)
            {
                Rectangle pageRectangle = GetRectangleOfPage(page + 1);
                if (bounds.IntersectsWith(pageRectangle))
                {
                    PdfSharp.Pdf.PdfPage pdfpage = document.AddPage();
                    pdfpage.Height = pageRectangle.Height;
                    pdfpage.Width  = pageRectangle.Width;
                    xg             = PdfSharp.Drawing.XGraphics.FromPdfPage(pdfpage);

                    Page p = (Page)m_layout.GetPages()[page];
                    p.PaintPdf(xg, pageRectangle, true, false);         //	sets context
                    m_layout.GetHeaderFooter().PaintPdf(xg, pageRectangle, true);
                    //p.Paint(g2D, pageRectangle, true, false);		//	sets context
                    //m_layout.GetHeaderFooter().Paint(g2D, pageRectangle, true);
                }
            }

            document.Save("D:\\Saved.pdf");
            document.Close();

            e.Graphics.DrawImageUnscaled(drawing, 0, 0);
            brush.Dispose();
            g2D.Dispose();
            this.AutoScrollMinSize = new System.Drawing.Size(this.GetPaperWidth(), this.GetPaperHeight() * m_layout.GetPages().Count() + (m_layout.GetPages().Count() * 5) + 10);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="pdfPath">pdf的地址</param>
 /// <param name="pdfImg">图片的地址</param>
 public void CreatePDF(string pdfPath, string pdfImg)
 {
     //测试路径
     System.Drawing.Image image4 = System.Drawing.Image.FromFile(pdfImg);
     using (PdfSharp.Pdf.PdfDocument pdf = new PdfSharp.Pdf.PdfDocument())
     {
         PdfSharp.Pdf.PdfPage ss = new PdfSharp.Pdf.PdfPage(pdf);
         double w = image4.Width * 0.75;
         double h = image4.Height * 0.75;
         ss.Width  = new XUnit(w);
         ss.Height = new XUnit(h);
         pdf.AddPage(ss);
         PdfSharp.Pdf.PdfPage page = pdf.Pages[0];
         XGraphics            gfx  = XGraphics.FromPdfPage(page);
         // Draw background
         gfx.DrawImage(PdfSharp.Drawing.XImage.FromFile(pdfImg), 0, 0);
         pdf.Save(pdfPath);
         pdf.Close();
     }
     image4.Dispose();
 }
Beispiel #10
0
 /// <summary>Add a new page if the current page is not empty</summary>
 public void addPage()
 {
     if (!_isPageEmpty)
     {
         if (_pageCount != 0)
         {
             addPagenumber();
         }
         _page = new PdfSharp.Pdf.PdfPage();
         if (_pageCount == 0)
         {
             _size.Width  = _page.Width;
             _size.Height = _page.Height;
             _area        = new PdfSharp.Drawing.XRect {
                 X      = PdfSharp.Drawing.XUnit.FromMillimeter(10),
                 Y      = PdfSharp.Drawing.XUnit.FromMillimeter(10),
                 Width  = _page.Width - PdfSharp.Drawing.XUnit.FromMillimeter(20),
                 Height = _page.Height - PdfSharp.Drawing.XUnit.FromMillimeter(45)
             };
         }
         else
         {
             _page        = new PdfSharp.Pdf.PdfPage();
             _page.Width  = _size.Width;
             _page.Height = _size.Height;
         }
         _horizontalePosition = _area.X;
         _verticalPosition    = _area.Y;
         _doc.AddPage(_page);
         if (_graphics != null)
         {
             _graphics.Dispose();
         }
         _graphics     = PdfSharp.Drawing.XGraphics.FromPdfPage(_page);
         _textformater = new PdfSharp.Drawing.Layout.XTextFormatter(_graphics);
         _pageCount++;
         _isPageEmpty = true;
     }
 }
Beispiel #11
0
        public void InitPdf()
        {
            // Create new PDF document
            this.Pdf = new PdfSharp.Pdf.PdfDocument();
            this.Pdf.Info.CreationDate = System.DateTime.Now.AddYears(-400);

            this.Pdf.Info.ModificationDate = new System.DateTime(System.DateTime.UtcNow.Ticks); // Throws exception on UTC time
            this.Pdf.Info.Title            = "PDFsharp SVG";
            this.Pdf.Info.Author           = "Stefan Steiger";
            this.Pdf.Info.Subject          = "SVG";


            System.Console.WriteLine(this.Pdf.Info.Producer);


            // Create new page
            PdfSharp.Pdf.PdfPage page = this.Pdf.AddPage();

            // Dimension
            page.Width  = PdfSharp.Drawing.XUnit.FromMillimeter(1000);
            page.Height = PdfSharp.Drawing.XUnit.FromMillimeter(1000);

            this.gfxPdf = PdfSharp.Drawing.XGraphics.FromPdfPage(page);
        }
Beispiel #12
0
        }     // End Sub CropPdf2

        static void CropPdf3(double page_width, double page_height)
        {
            string fn = @"D:\username\Desktop\0001 Altstetten - GB01 H602 - OG14.pdf";

            // fn = @"D:\username\Desktop\0030 Sentimatt - GB01 Sentimatt - EG00.pdf";
            fn = @"D:\username\Desktop\Altstetten_1_50.pdf";


            // The current implementation of PDFsharp has only one layout of the graphics context.
            // The origin(0, 0) is top left and coordinates grow right and down.
            // The unit of measure is always point (1 / 72 inch).

            // 1 pt = 0,0352778 cm
            // 1 pt = 0,352778 mm
            // 1 inch = 2,54 cm
            // 1/72 inch to cm = 0,035277777777777776 cm


            // A0:
            // w: 2384 pt =  84,10222 cm
            // h: 3370 pt = 118,8861  cm

            // A3:
            // w:  842 pt = 29,7039  cm
            // h: 1191 pt = 42,01583 cm

            // A4:
            // 595 pt to cm = 20,9903 w
            // 842 pt to cm = 29,7039 h



            // A0
            page_width  = 2384;
            page_height = 3370;

            // A3
            page_width  = 842;
            page_height = 1191;

            // A4
            page_width  = 595;
            page_height = 842;

            PdfMargin margin = new PdfMargin(mm2pt(10)); // 1cm in pt


            double crop_width  = page_width - margin.Left - margin.Right;
            double crop_height = page_height - margin.Top - margin.Bottom;


            using (PdfSharp.Drawing.XPdfForm sourceForm = PdfSharp.Drawing.XPdfForm.FromFile(fn))
            {
                sourceForm.PageNumber = 1;
                int numHori  = (int)System.Math.Ceiling(sourceForm.Page.Width.Point / crop_width);
                int numVerti = (int)System.Math.Ceiling(sourceForm.Page.Height.Point / crop_height);

                PdfSharp.Drawing.XRect pageDimenstions = new PdfSharp.Drawing.XRect(0, 0, sourceForm.Page.Width, sourceForm.Page.Height);

                using (PdfSharp.Pdf.PdfDocument destDocument = new PdfSharp.Pdf.PdfDocument())
                {
                    for (int iverti = 0; iverti < numVerti; iverti++)
                    {
                        for (int ihori = 0; ihori < numHori; ihori++)
                        {
                            PdfSharp.Pdf.PdfPage destPage = destDocument.AddPage();
                            destPage.Width  = crop_width;
                            destPage.Height = crop_height;

                            PdfSharp.Drawing.XRect cropRect = new PdfSharp.Drawing.XRect(ihori * crop_width, iverti * crop_height, sourceForm.Page.Width, sourceForm.Page.Height);

                            using (PdfSharp.Drawing.XGraphics destGFX = PdfSharp.Drawing.XGraphics.FromPdfPage(destPage))
                            {
                                destGFX.DrawImageCropped(sourceForm, cropRect, pageDimenstions, PdfSharp.Drawing.XGraphicsUnit.Point);
                            } // End Using destGFX
                        }     // ihori
                    }         // iverti

                    // destDocument.Save("chopped.pdf");

                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        destDocument.Save(ms);
                        ms.Position = 0;

                        using (PdfSharp.Drawing.XPdfForm croppedImages = PdfSharp.Drawing.XPdfForm.FromStream(ms))
                        {
                            using (PdfSharp.Pdf.PdfDocument finalDestination = new PdfSharp.Pdf.PdfDocument())
                            {
                                PdfSharp.Drawing.XFont font = new PdfSharp.Drawing.XFont("Arial", 8);

                                for (int i = 0; i < croppedImages.PageCount; ++i)
                                {
                                    PdfSharp.Pdf.PdfPage targetPage = finalDestination.AddPage();
                                    targetPage.Width  = page_width;
                                    targetPage.Height = page_height;

                                    PdfSharp.Drawing.XRect pageSize = new PdfSharp.Drawing.XRect(0, 0, targetPage.Width, targetPage.Height);

                                    try
                                    {
                                        croppedImages.PageIndex = i;

                                        using (PdfSharp.Drawing.XGraphics targetGFX = PdfSharp.Drawing.XGraphics.FromPdfPage(targetPage))
                                        {
#if DEBUG_ME
                                            targetGFX.DrawRectangle(XBrushes.Honeydew, pageSize);
#endif

                                            PdfSharp.Drawing.XRect targetRect = new PdfSharp.Drawing.XRect(margin.Left, margin.Top, crop_width, crop_height);

                                            targetGFX.DrawImage(croppedImages, targetRect, targetRect, PdfSharp.Drawing.XGraphicsUnit.Point);

                                            DrawBorder(targetGFX, targetPage.Width.Point, targetPage.Height.Point, margin);
                                            DrawCrosshairs(targetGFX, targetPage.Width.Point, targetPage.Height.Point, margin);

                                            // int numHori = (int)System.Math.Ceiling(sourceForm.Page.Width / crop_width);
                                            // int numVerti = (int)System.Math.Ceiling(sourceForm.Page.Height / crop_height);

                                            int col = i % numHori;
                                            int row = i / numHori;

                                            // targetGFX.DrawString($"Column {col + 1}/{numHori} Row {row + 1}/{numVerti}, Page {i + 1}/{croppedImages.PageCount}", font, PdfSharp.Drawing.XBrushes.Black, margin.Left + 5, targetPage.Height.Point - margin.Bottom + font.Size + 5);
                                            targetGFX.DrawString($"Spalte {col + 1}/{numHori} Zeile {row + 1}/{numVerti}, Seite {i + 1}/{croppedImages.PageCount}", font, PdfSharp.Drawing.XBrushes.Black, margin.Left + 5, targetPage.Height.Point - margin.Bottom + font.Size + 5);
                                        } // End using targetGFX
                                    }
                                    catch (System.Exception ex)
                                    {
                                        System.Console.WriteLine(croppedImages.PageIndex);
                                        System.Console.WriteLine(ex.Message);
                                    }
                                } // Next i

                                finalDestination.Save("CropPdf3.pdf");
                            } // End Using finalDestination
                        }     // End Using croppedImages
                    }         // End Using ms
                }             // End Using destDocument
            }                 // End Using sourceForm
        }                     // End Sub CropPdf3
Beispiel #13
0
        static void WriteTest()
        {
            using (PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument())
            {
                document.Info.Title    = "Family Tree";
                document.Info.Author   = "FamilyTree Ltd. - Stefan Steiger";
                document.Info.Subject  = "Family Tree";
                document.Info.Keywords = "Family Tree, Genealogical Tree, Genealogy, Bloodline, Pedigree";


                PdfSharp.Pdf.Security.PdfSecuritySettings securitySettings = document.SecuritySettings;

                // Setting one of the passwords automatically sets the security level to
                // PdfDocumentSecurityLevel.Encrypted128Bit.
                securitySettings.UserPassword  = "******";
                securitySettings.OwnerPassword = "******";

                // Don't use 40 bit encryption unless needed for compatibility
                //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

                // Restrict some rights.
                securitySettings.PermitAccessibilityExtractContent = false;
                securitySettings.PermitAnnotations      = false;
                securitySettings.PermitAssembleDocument = false;
                securitySettings.PermitExtractContent   = false;
                securitySettings.PermitFormsFill        = true;
                securitySettings.PermitFullQualityPrint = false;
                securitySettings.PermitModifyDocument   = true;
                securitySettings.PermitPrint            = false;



                document.ViewerPreferences.Direction = PdfSharp.Pdf.PdfReadingDirection.LeftToRight;
                PdfSharp.Pdf.PdfPage page = document.AddPage();

                // page.Width = PdfSettings.PaperFormatSettings.Width
                // page.Height = PdfSettings.PaperFormatSettings.Height

                page.Orientation = PdfSharp.PageOrientation.Landscape;
                double dblLineWidth = 1.0;
                string strHtmlColor = "#FF00FF";
                PdfSharp.Drawing.XColor lineColor = XColorHelper.FromHtml(strHtmlColor);
                PdfSharp.Drawing.XPen   pen       = new PdfSharp.Drawing.XPen(lineColor, dblLineWidth);

                PdfSharp.Drawing.XFont font = new PdfSharp.Drawing.XFont("Arial"
                                                                         , 12.0, PdfSharp.Drawing.XFontStyle.Bold
                                                                         );



                using (PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page))
                {
                    gfx.MUH = PdfSharp.Pdf.PdfFontEncoding.Unicode;

                    PdfSharp.Drawing.Layout.XTextFormatter tf = new PdfSharp.Drawing.Layout.XTextFormatter(gfx);
                    tf.Alignment = PdfSharp.Drawing.Layout.XParagraphAlignment.Left;

                    PdfSharp.Drawing.Layout.XTextFormatterEx2 etf = new PdfSharp.Drawing.Layout.XTextFormatterEx2(gfx);


                    gfx.DrawRectangle(pen, new PdfSharp.Drawing.XRect(100, 100, 100, 100));

                    using (PdfSharp.Drawing.XImage img = PdfSharp.Drawing.XImage.FromFile(@"D:\username\Documents\Visual Studio 2017\Projects\PdfSharp\TestApplication\Wikipedesketch1.png"))
                    {
                        gfx.DrawImage(img, 500, 500);
                    }

                    string text = "Lalala";

                    tf.DrawString(text
                                  , font
                                  , PdfSharp.Drawing.XBrushes.Black
                                  , new PdfSharp.Drawing.XRect(300, 300, 100, 100)
                                  , PdfSharp.Drawing.XStringFormats.TopLeft
                                  );
                } // End Using gfx

                // Save the document...
                string filename = "TestFilePwProtected.pdf";
                document.Save(filename);
                // ...and start a viewer.
                System.Diagnostics.Process.Start(filename);
            } // End Using document
        }     // End Sub WriteTest
Beispiel #14
0
        public static void ReadPdf()
        {
            // Get a fresh copy of the sample PDF file
            string filename = @"C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\R_SERVICES\doc\manual\R-intro.pdf";

            // Create the output document
            PdfSharp.Pdf.PdfDocument outputDocument =
                new PdfSharp.Pdf.PdfDocument();

            // Show single pages
            // (Note: one page contains two pages from the source document)
            outputDocument.PageLayout = PdfSharp.Pdf.PdfPageLayout.SinglePage;

            /*
             * PdfSharp.Drawing.XFont font =
             *  new PdfSharp.Drawing.XFont("Verdana", 8, PdfSharp.Drawing.XFontStyle.Bold);
             * PdfSharp.Drawing.XStringFormat format = new PdfSharp.Drawing.XStringFormat();
             * format.Alignment = PdfSharp.Drawing.XStringAlignment.Center;
             * format.LineAlignment = PdfSharp.Drawing.XLineAlignment.Far;
             */
            PdfSharp.Drawing.XGraphics gfx;
            PdfSharp.Drawing.XRect     box;

            // Open the external document as XPdfForm object
            PdfSharp.Drawing.XPdfForm form =
                PdfSharp.Drawing.XPdfForm.FromFile(filename);

            for (int idx = 0; idx < form.PageCount; idx += 2)
            {
                // Add a new page to the output document
                PdfSharp.Pdf.PdfPage page = outputDocument.AddPage();
                page.Orientation = PdfSharp.PageOrientation.Landscape;
                double width  = page.Width;
                double height = page.Height;

                int rotate = page.Elements.GetInteger("/Rotate");

                gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page);

                // Set page number (which is one-based)
                form.PageNumber = idx + 1;

                box = new PdfSharp.Drawing.XRect(0, 0, width / 2, height);
                // Draw the page identified by the page number like an image
                gfx.DrawImage(form, box);


                // Write document file name and page number on each page
                box.Inflate(0, -10);

                /*
                 * gfx.DrawString(string.Format("- {1} -", filename, idx + 1),
                 *   font, PdfSharp.Drawing.XBrushes.Red, box, format);
                 */
                if (idx + 1 < form.PageCount)
                {
                    // Set page number (which is one-based)
                    form.PageNumber = idx + 2;

                    box = new PdfSharp.Drawing.XRect(width / 2, 0, width / 2, height);
                    // Draw the page identified by the page number like an image
                    gfx.DrawImage(form, box);

                    // Write document file name and page number on each page
                    box.Inflate(0, -10);

                    /*
                     * gfx.DrawString(string.Format("- {1} -", filename, idx + 2),
                     *  font, PdfSharp.Drawing.XBrushes.Red, box, format);
                     */
                }
            }

            // Save the document...
            filename = "TwoPagesOnOne_tempfile.pdf";
            outputDocument.Save(filename);
            // ...and start a viewer.
            System.Diagnostics.Process.Start(filename);
        }
        public void exportSertificatesAndPrilozenia(string sourcePDFFilePath, string outFolderPath, List <Tesseract_OCR.Tesseract_OCR_Window.pdfPageInfo> infoPages)
        {
            //создаем путь для выходных обработанных изображений
            System.IO.Directory.CreateDirectory(outFolderPath);

            // open and load the file
            using (PdfSharp.Pdf.PdfDocument inputDocument = PdfReader.Open(sourcePDFFilePath, PdfDocumentOpenMode.Import))
            {
                //создаем pdf документ
                PdfSharp.Pdf.PdfDocument pdfDocSertAndPril = null;

                // process and save pages one by one
                //for (int i = 0; i < infoPages.Count; i++)
                for (int i = 0; i < inputDocument.PageCount; i++)
                {
                    if ((infoPages[i].typeOfPage_ == Tesseract_OCR_Window.typeOfPage.SERTIFICATE) || (infoPages[i].typeOfPage_ == Tesseract_OCR_Window.typeOfPage.PRILOZENIE))
                    {
                        //путь к выходной папке серта
                        string outSertFolder = "";

                        //путь к выходному файлу серта
                        string outSertFilePath = "";

                        //путь к выходному файлу (серт + приложения к нему)
                        string outSertAndPrilFilePath = "";

                        //раскидываем по папкам "распознано/не распознано"
                        if (infoPages[i].isTesseracted_ == true)
                        {
                            outSertFolder   = outFolderPath + "\\" + "[+]Tesseracted" + "\\" + infoPages[i].fullNumber_;
                            outSertFilePath = outFolderPath + "\\" + "[+]Tesseracted" + "\\" + infoPages[i].fullNumber_ + "\\" + infoPages[i].fullNumber_ + ".pdf";

                            outSertAndPrilFilePath = outFolderPath + "\\" + "[+]Tesseracted" + "\\" + infoPages[i].fullNumber_ + "\\" + "[FULL]" + infoPages[i].fullNumber_ + ".pdf";
                        }
                        else
                        {
                            outSertFolder   = outFolderPath + "\\" + "[-]Tesseracted" + "\\" + infoPages[i].fullNumber_;
                            outSertFilePath = outFolderPath + "\\" + "[-]Tesseracted" + "\\" + infoPages[i].fullNumber_ + "\\" + infoPages[i].fullNumber_ + ".pdf";

                            outSertAndPrilFilePath = outFolderPath + "\\" + "[-]Tesseracted" + "\\" + infoPages[i].fullNumber_ + "\\" + "[FULL]" + infoPages[i].fullNumber_ + ".pdf";
                        }

                        if (System.IO.Directory.Exists(outSertFolder))
                        {
                            int indexOfNewFolder = 2;

                            do
                            {
                                //раскидываем по папкам "распознано/не распознано"
                                if (infoPages[i].isTesseracted_ == true)
                                {
                                    outSertFolder   = outFolderPath + "\\" + "[+]Tesseracted" + "\\[" + indexOfNewFolder + "]" + infoPages[i].fullNumber_;
                                    outSertFilePath = outFolderPath + "\\" + "[+]Tesseracted" + "\\[" + indexOfNewFolder + "]" + infoPages[i].fullNumber_ + "\\" + infoPages[i].fullNumber_ + ".pdf";

                                    outSertAndPrilFilePath = outFolderPath + "\\" + "[+]Tesseracted" + "\\[" + indexOfNewFolder + "]" + infoPages[i].fullNumber_ + "\\" + "[FULL]" + infoPages[i].fullNumber_ + ".pdf";
                                }
                                else
                                {
                                    outSertFolder   = outFolderPath + "\\" + "[-]Tesseracted" + "\\[" + indexOfNewFolder + "]" + infoPages[i].fullNumber_;
                                    outSertFilePath = outFolderPath + "\\" + "[-]Tesseracted" + "\\[" + indexOfNewFolder + "]" + infoPages[i].fullNumber_ + "\\" + infoPages[i].fullNumber_ + ".pdf";

                                    outSertAndPrilFilePath = outFolderPath + "\\" + "[-]Tesseracted" + "\\[" + indexOfNewFolder + "]" + infoPages[i].fullNumber_ + "\\" + "[FULL]" + infoPages[i].fullNumber_ + ".pdf";
                                }

                                indexOfNewFolder++;
                            } while((System.IO.Directory.Exists(outSertFolder)) == true);
                            //если уже есть такая папка, то добавляем префикс
                            System.IO.Directory.CreateDirectory(outSertFolder);
                        }
                        else
                        {
                            //создаем папку с названием сертификата, содержащую сам серт и приложения
                            System.IO.Directory.CreateDirectory(outSertFolder);
                        }

                        //даем права на запись в папку
                        File.SetAttributes(outSertFolder, FileAttributes.Normal);

                        //цепляем страницу серта
                        PdfSharp.Pdf.PdfPage pageSert = inputDocument.Pages[i];

                        //создаем pdf документ
                        PdfSharp.Pdf.PdfDocument pdfDocSert = new PdfSharp.Pdf.PdfDocument();
                        pdfDocSertAndPril = new PdfSharp.Pdf.PdfDocument();

                        //добавляем в pdf документ сертификат
                        pdfDocSert.AddPage(pageSert);
                        pdfDocSertAndPril.AddPage(pageSert);

                        //сохраняем pdf файл
                        pdfDocSert.Save(outSertFilePath);

                        //проверка на выход за границу контейнера infoPages
                        //if((i + 1) >= infoPages.Count){
                        if ((i + 1) >= inputDocument.PageCount)
                        {
                            pdfDocSertAndPril.Save(outSertAndPrilFilePath);

                            //очищаем
                            pdfDocSertAndPril.Dispose();
                            pdfDocSert.Dispose();

                            continue;
                        }

                        //для смены позиции индекса в документе
                        int updatePositionInDoc = -1;

                        //for (int j = i + 1; j < infoPages.Count; j++)
                        for (int j = i + 1; j < inputDocument.PageCount; j++)
                        {
                            if (infoPages[j].typeOfPage_ == Tesseract_OCR_Window.typeOfPage.PRILOZENIE)
                            {
                                //путь к выходному файлу приложения
                                //string outPrilozenieFilePath = outFolderPath + "\\" + infoPages[i].fullNumber_ + "\\" + infoPages[i].fullNumber_ + "." + infoPages[j].seriaNumber_ + ".pdf";
                                string outPrilozenieFilePath = outSertFolder + "\\" + infoPages[i].fullNumber_ + "." + infoPages[j].seriaNumber_ + ".pdf";

                                //цепляем страницу приложения
                                PdfSharp.Pdf.PdfPage pagePrilozenie = inputDocument.Pages[j];

                                //создаем pdf документ
                                PdfSharp.Pdf.PdfDocument pdfDocPrilozenie = new PdfSharp.Pdf.PdfDocument();

                                //добавляем в pdf документ приложение
                                pdfDocPrilozenie.AddPage(pagePrilozenie);
                                pdfDocSertAndPril.AddPage(pagePrilozenie);

                                //сохраняем pdf файл
                                if (File.Exists(outPrilozenieFilePath))
                                {
                                    int offsetIndex = 1;

                                    do
                                    {
                                        outPrilozenieFilePath = outSertFolder + "\\[" + offsetIndex + "]" + infoPages[i].fullNumber_ + "." + infoPages[j].seriaNumber_ + ".pdf";

                                        offsetIndex++;
                                    } while(File.Exists(outPrilozenieFilePath));
                                }

                                pdfDocPrilozenie.Save(outPrilozenieFilePath);

                                //увеличиваем кол-во считанных страниц в документе
                                updatePositionInDoc = j;
                            }
                            else
                            {
                                //если это серт, то отматываемся, т.к. его обработка идет не здесь
                                i = j - 1;

                                break;
                            }
                        }

                        //если меняли значение, то обновляем позицию в документе
                        if (updatePositionInDoc != -1)
                        {
                            //меняем позицию в документе
                            i = updatePositionInDoc;
                        }

                        pdfDocSertAndPril.Save(outSertAndPrilFilePath);

                        //очищаем
                        pdfDocSertAndPril.Dispose();
                        pdfDocSert.Dispose();
                    }
                }
            }
        }
Beispiel #16
0
        public static void CropPdf1(double crop_width, double crop_height)
        {
            string fn = @"D:\username\Desktop\0001 Altstetten - GB01 H602 - OG14.pdf";

            // fn = @"D:\username\Desktop\0030 Sentimatt - GB01 Sentimatt - EG00.pdf";


            // The current implementation of PDFsharp has only one layout of the graphics context.
            // The origin(0, 0) is top left and coordinates grow right and down.
            // The unit of measure is always point (1 / 72 inch).

            // 1 pt = 0,0352778 cm
            // 1 pt = 0,352778 mm
            // 1 inch = 2,54 cm
            // 1/72 inch to cm = 0,035277777777777776 cm


            // A0:
            // w: 2384 pt =  84,10222 cm
            // h: 3370 pt = 118,8861  cm

            // A3:
            // w:  842 pt = 29,7039  cm
            // h: 1191 pt = 42,01583 cm

            // A4:
            // 595 pt to cm = 20,9903 w
            // 842 pt to cm = 29,7039 h


            using (PdfSharp.Drawing.XPdfForm sourceForm = PdfSharp.Drawing.XPdfForm.FromFile(fn))
            {
                sourceForm.PageNumber = 1;

                int numHori  = (int)System.Math.Ceiling(sourceForm.Page.Width.Point / crop_width);
                int numVerti = (int)System.Math.Ceiling(sourceForm.Page.Height.Point / crop_height);
                PdfSharp.Drawing.XRect pageDimenstions = new PdfSharp.Drawing.XRect(0, 0, sourceForm.Page.Width.Point, sourceForm.Page.Height.Point);


                // Crop the PDF - HAS NO EFFECT...
                // sourceForm.Page.CropBox = new PdfSharp.Pdf.PdfRectangle(cropDim);

                using (PdfSharp.Pdf.PdfDocument destDocument = new PdfSharp.Pdf.PdfDocument())
                {
                    for (int iverti = 0; iverti < numHori; iverti++)
                    {
                        for (int ihori = 0; ihori < numHori; ihori++)
                        {
                            PdfSharp.Pdf.PdfPage destPage = destDocument.AddPage();
                            destPage.Width  = sourceForm.Page.Width;
                            destPage.Height = sourceForm.Page.Height;


                            PdfSharp.Drawing.XRect cropDim = new PdfSharp.Drawing.XRect(ihori * crop_width, iverti * crop_height, crop_width, crop_height);

                            PdfSharp.Drawing.XRect cropRect = new PdfSharp.Drawing.XRect(cropDim.X, destPage.Height.Point - cropDim.Height - cropDim.Y, cropDim.Width, cropDim.Height);

                            using (PdfSharp.Drawing.XGraphics destGFX = PdfSharp.Drawing.XGraphics.FromPdfPage(destPage))
                            {
                                destGFX.DrawImage(sourceForm, pageDimenstions);
                                destGFX.DrawRectangle(PdfSharp.Drawing.XPens.DeepPink, cropDim);
                            } // End Using destGFX

                            // PdfSharp.Drawing.XRect cropRect1 = new PdfSharp.Drawing.XRect(cropRect.X - 30, cropRect.Y - 30, cropRect.Width + 30, cropRect.Height + 30);

                            destPage.CropBox = new PdfSharp.Pdf.PdfRectangle(cropRect);
                            // destPage.MediaBox = new PdfSharp.Pdf.PdfRectangle(cropRect1);

                            // destPage.CropBox = new PdfSharp.Pdf.PdfRectangle(new XPoint(cropDim.X, destPage.Height - cropDim.Height - cropDim.Y),
                            //                      new XSize(cropDim.Width, cropDim.Height));
                        } // Next ihori
                    }     // Next iverti

                    destDocument.Save("CropPdf1.pdf");
                } // End Using gfx
            }     // End Using document
        }         // End Sub CropPdf1
Beispiel #17
0
        static void PdfSharpTestParsePage(PdfSharp.Pdf.PdfPage page)
        {
            foreach (String currentPageElementKey in page.Elements.Keys)
            {
                System.Diagnostics.Debug.WriteLine("[Page Element:" + currentPageElementKey + "] " + page.Elements [currentPageElementKey].ToString());
            }



            PdfSharp.Pdf.PdfDictionary pageResources = page.Elements.GetDictionary("/Resources");

            if (pageResources != null)
            {
                PdfSharp.Pdf.PdfDictionary pageObjects = pageResources.Elements.GetDictionary("/XObject");
            }



            PdfSharp.Pdf.PdfDictionary pageFonts = pageResources.Elements.GetDictionary("/Font");


            foreach (String currentElementKey in pageFonts.Elements.Keys)
            {
                System.Diagnostics.Debug.WriteLine("[FONT:" + currentElementKey + "]");

                PdfSharp.Pdf.Advanced.PdfReference fontReference = pageFonts.Elements[currentElementKey] as PdfSharp.Pdf.Advanced.PdfReference;

                PdfSharp.Pdf.PdfDictionary fontDictionary = fontReference.Value as PdfSharp.Pdf.PdfDictionary;

                foreach (String fontElementKey in fontDictionary.Elements.Keys)
                {
                    String propertyName = fontElementKey;

                    String propertyValue = fontDictionary.Elements [fontElementKey].ToString();

                    System.Diagnostics.Debug.WriteLine("[FONT:" + currentElementKey + "] | [" + propertyName + ":" + propertyValue + "]");

                    if (propertyName == "/FontDescriptor")
                    {
                        Int32 fontDescriptorObjectId = Convert.ToInt32(propertyValue.Split(' ')[0]);

                        PdfSharp.Pdf.PdfObject fontDescriptor = PdfSharpGetItem(page.Owner, fontDescriptorObjectId);

                        System.Diagnostics.Debug.WriteLine("DESCRIPTOR (BEGIN)");

                        foreach (String descriptorElementKey in (fontDescriptor as PdfSharp.Pdf.PdfDictionary).Elements.Keys)
                        {
                            propertyName = descriptorElementKey;

                            propertyValue = (fontDescriptor as PdfSharp.Pdf.PdfDictionary).Elements[descriptorElementKey].ToString();

                            System.Diagnostics.Debug.WriteLine("[FONT:" + currentElementKey + "] | [" + propertyName + ":" + propertyValue + "]");
                        }

                        System.Diagnostics.Debug.WriteLine("DESCRIPTOR ( END )");
                    }
                }
            }



            return;
        }
Beispiel #18
0
        private void obrotPdf(int rotateAngle)
        {
            axAcroPDF1.src = "";
            int rot;

            PdfSharp.Pdf.PdfDocument pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(activeFolder + activeFile, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify);
            pdfDoc.Tag = "UNIMAP";

            for (int i = 0; i < pdfDoc.PageCount; i++)
            {
                PdfSharp.Pdf.PdfPage page = pdfDoc.Pages[i];

                PdfSharp.PageOrientation po = page.Orientation;

                rot = page.Rotate + rotateAngle;

                /*
                 * if (rot <= -180)
                 *  rot += 180;
                 * else if (rot > 180)
                 *  rot -= 180;
                 */

                if (rot < 0)
                {
                    rot += 360;
                }
                else if (rot >= 360)
                {
                    rot -= 360;
                }

                // MessageBox.Show(page.Rotate.ToString());
                page.Rotate = rot;
                //MessageBox.Show(page.Rotate.ToString());

                //gdy page.Rotate jest 90 lub -90 to automatycznie zmienia się układ strony, gdy 180 to nie i zostaje stary układ trzeba go zmienić ręcznie....

                if ((Math.Abs(rotateAngle) == 90) || (rotateAngle == 270))
                {
                    if ((Math.Abs(page.Rotate) == 180) || (Math.Abs(page.Rotate) == 0))
                    {
                        if (po == PdfSharp.PageOrientation.Portrait)
                        {
                            page.Orientation = PdfSharp.PageOrientation.Landscape;
                        }
                        else
                        {
                            page.Orientation = PdfSharp.PageOrientation.Portrait;
                        }
                    }
                }
                else if ((Math.Abs(rotateAngle) == 180) || (rotateAngle == 0))
                {
                    if ((Math.Abs(page.Rotate) == 90) || (Math.Abs(page.Rotate) == 270))
                    {
                        if (po == PdfSharp.PageOrientation.Portrait)
                        {
                            page.Orientation = PdfSharp.PageOrientation.Landscape;
                        }
                        else
                        {
                            page.Orientation = PdfSharp.PageOrientation.Portrait;
                        }
                    }
                }
            }

            pdfDoc.Save(activeFolder + activeFile);

            axAcroPDF1.src = activeFolder + activeFile;
            Application.DoEvents();
        }
Beispiel #19
0
        /// <summary>
        /// Create PDF-document
        /// </summary>
        /// <param name="folder"></param>
        /// <returns>Path to saved document</returns>
        public string Create(string folder, InformativeExport informativeExport)
        {
            this.documentFile = informativeExport.documentFile;
            this.mapFile      = informativeExport.mapFile;
            this.baseLayer    = informativeExport.baseMapId;

            string file       = String.Format("{0}App_Data\\{1}", HostingEnvironment.ApplicationPhysicalPath, this.layersFile);
            var    layersJson = System.IO.File.ReadAllText(file);

            this.layers = JsonConvert.DeserializeObject <LayerConfig>(layersJson);

            string mapFile = String.Format("{0}App_Data\\{1}", HostingEnvironment.ApplicationPhysicalPath, this.mapFile);
            var    mapJson = System.IO.File.ReadAllText(mapFile);

            this.mapConfig = JsonConvert.DeserializeObject <MapConfig>(mapJson);
            Tool t = this.mapConfig.tools.Find(tool => tool.type == "layerswitcher");

            if (t != null)
            {
                this.layerSwitcherOptions = JsonConvert.DeserializeObject <LayerSwitcherOptions>(t.options.ToString());
            }

            // Some operations will use the tmp-folder. Created files are deleted when used.
            Directory.CreateDirectory("C:\\tmp");

            // Load informative document
            string documentFile   = String.Format("{0}App_Data\\documents\\{1}", HostingEnvironment.ApplicationPhysicalPath, this.documentFile);
            string documentJson   = System.IO.File.ReadAllText(documentFile);
            var    exportDocument = JsonConvert.DeserializeObject <Document>(documentJson);

            StringBuilder html = new StringBuilder();

            String.Format("{0}App_Data\\documents\\{1}", HostingEnvironment.ApplicationPhysicalPath, this.documentFile);

            html.AppendLine("<head>");
            html.AppendLine("<meta charset='UTF-8'>");
            html.AppendLine("</head>");
            html.AppendLine("<body>");
            html.AppendLine("<style>");
            html.AppendLine("body { font-family: arial; font-size: 13pt !important;}");
            html.AppendLine("body img { width: 100%; }");
            html.AppendLine("</style>");

            // Append maps to document
            this.totalChapters = GetTotalChapters(exportDocument.chapters.ToList(), 0);
            this.AppendHtml(exportDocument.chapters.ToList(), ref html);
            html.AppendLine("</body>");

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.Margins.Bottom = 15;
            htmlToPdf.Margins.Top    = 15;

            htmlToPdf.PageFooterHtml = "<div style='text-align:center;'><span class='page'></span> </div>";
            var pdfBytes1 = htmlToPdf.GeneratePdf(html.ToString());

            //
            // Read the created document and match headers to create toc.
            // Headers must be unique
            //
            string tocHtml = "";

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pdfBytes1);

            Dictionary <int, string[]> pageContents = new Dictionary <int, string[]>();

            for (int j = 1; j <= reader.NumberOfPages; j++)
            {
                string text = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, j);
                pageContents.Add(j, text.Split('\n'));
            }
            tocHtml += "<head>";
            tocHtml += "<meta charset='UTF-8'>";
            tocHtml += "</head>";
            tocHtml += "<body>";
            tocHtml += "<style>";
            tocHtml += "body { font-family: arial; font-size: 13pt !important;}";
            tocHtml += "body img { width: 100%; }";
            tocHtml += "</style>";
            tocHtml += "<h1>Innehållsförteckning</h1>";

            this.AppendHeader(exportDocument.chapters.ToList(), ref tocHtml, pageContents);

            tocHtml += "</body>";

            htmlToPdf.PageFooterHtml = "";
            var pdfBytes2 = htmlToPdf.GeneratePdf(tocHtml.ToString());

            MemoryStream stream1 = new MemoryStream(pdfBytes1);
            MemoryStream stream2 = new MemoryStream(pdfBytes2);

            PdfSharp.Pdf.PdfDocument inputDocument1 = PdfSharp.Pdf.IO.PdfReader.Open(stream1, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
            PdfSharp.Pdf.PdfDocument inputDocument2 = PdfSharp.Pdf.IO.PdfReader.Open(stream2, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

            List <PdfSharp.Pdf.PdfDocument> inputDocuments = new List <PdfSharp.Pdf.PdfDocument>();

            inputDocuments.Add(inputDocument2);
            inputDocuments.Add(inputDocument1);

            //
            // Remove unwanted pages.
            // Pages within the same chapter will remain.
            //
            List <Chapter> flattened = new List <Chapter>();

            FlattenChapters(exportDocument.chapters, ref flattened);
            int chapterCount = 0;

            this.SetChapterPages(exportDocument.chapters, flattened, ref chapterCount);
            int initialPageCount = inputDocument1.Pages.Count;

            this.RemoveSurroundingPages(informativeExport.chapterHeader, informativeExport.chapterHtml, exportDocument.chapters, inputDocument1);
            int modifiedPageCount = inputDocument1.Pages.Count;

            if (initialPageCount == modifiedPageCount)
            {
                this.RemoveLastPage(inputDocument1);
            }

            inputDocuments.ForEach(document =>
            {
                int count = document.PageCount;
                for (int idx = 0; idx < count; idx++)
                {
                    PdfSharp.Pdf.PdfPage page = document.Pages[idx];
                    outputDocument.AddPage(page);
                }
            });

            reader.Close();
            stream1.Close();
            stream2.Close();

            var    r         = new Random();
            var    i         = r.Next();
            string fileName  = "pdf-export-" + i + ".pdf";
            string localFile = HostingEnvironment.ApplicationPhysicalPath + "//Temp//" + fileName;

            outputDocument.Save(localFile);

            return(fileName);
        }
Beispiel #20
0
        private void printPreview(List <string> prInfo)
        {
            string newPath     = Directory.GetCurrentDirectory().Replace("bin\\Debug", "PersonalRecords\\");
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            Array.ForEach(Directory.GetFiles(@"" + newPath + "\\AthleteNameAdded\\"), File.Delete);
            string fileNameTemplate = @"" + newPath + "Template.pdf";

            string[] meetInfo      = getMeetInfo();
            int      textSpacing   = 7;
            int      textAlignment = PdfContentByte.ALIGN_CENTER;

            string[] prInfoArray = prInfo.ToArray();
            for (int i = 0; i < prInfoArray.Length - 1; i++)
            {
                if (i % 8 == 0)
                {
                    int    fileCount_Ath        = Directory.GetFiles(newPath + "\\AthleteNameAdded", "*", SearchOption.TopDirectoryOnly).Length;
                    string fileNameAthleteAdded = @"" + newPath + "\\AthleteNameAdded\\testAthleteAddedCopy" + fileCount_Ath + ".pdf";

                    using (var reader = new iTextSharp.text.pdf.PdfReader(@"" + fileNameTemplate))
                        using (var fileStream = new FileStream(@"" + fileNameAthleteAdded, FileMode.Create, FileAccess.Write))
                        {
                            var document = new Document(reader.GetPageSizeWithRotation(1));
                            var writer   = PdfWriter.GetInstance(document, fileStream);

                            document.Open();

                            document.NewPage();

                            var baseFont     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                            var importedPage = writer.GetImportedPage(reader, 1);

                            var contentByte = writer.DirectContent;
                            contentByte.BeginText();
                            contentByte.SetFontAndSize(baseFont, 12);
                            string meetDate = meetInfo[1].Split(' ')[0];

                            //text to be added---The /NAME/
                            var athleteName = prInfoArray[i] + " " + prInfoArray[i + 1];
                            //adds in the name
                            int x = 225;
                            foreach (var line in athleteName)
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x, 593, 0);
                                x = x + textSpacing;
                            }

                            var trackEvent = prInfoArray[i + 2];

                            //adds in the event
                            int x2 = 157;
                            foreach (var line in trackEvent)
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x2, 537, 0);
                                x2 = x2 + textSpacing;
                            }

                            //adds in the time/distance
                            contentByte.ShowTextAligned(textAlignment, formatMark(prInfoArray, i, 3), x2 + 30, 537, 0);

                            //adds in the meet name
                            int x5 = 157;
                            foreach (var line in meetInfo[0])
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x5, 510, 0);
                                x5 = x5 + textSpacing;
                            }

                            //adds in the meet date
                            int x6 = 240;
                            foreach (var line in meetDate)
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x6, 483, 0);
                                x6 = x6 + textSpacing;
                            }


                            //-----------------------second pr-----------------------------------------------------
                            try
                            {
                                var athleteName2 = prInfoArray[i + 4] + " " + prInfoArray[i + 5];
                                //adds in the athlete name
                                int x3 = 225;
                                foreach (var line in athleteName2)
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x3, 205, 0);
                                    x3 = x3 + textSpacing;
                                }

                                var trackEvent2 = prInfoArray[i + 6];
                                //adds in the event
                                int x4 = 157;
                                foreach (var line in trackEvent2)
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x4, 149, 0);
                                    x4 = x4 + textSpacing;
                                }

                                //adds in the time/distance
                                contentByte.ShowTextAligned(textAlignment, formatMark(prInfoArray, i, 7), x4 + 30, 149, 0);

                                //adds in the meet name
                                int x7 = 157;
                                foreach (var line in meetInfo[0])
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x7, 122, 0);
                                    x7 = x7 + textSpacing;
                                }

                                //adds in the meet date
                                int x8 = 240;
                                foreach (var line in meetDate)
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x8, 95, 0);
                                    x8 = x8 + textSpacing;
                                }

                                contentByte.EndText();
                                contentByte.AddTemplate(importedPage, 0, 0);


                                document.Close();
                                writer.Close();
                            }
                            catch (Exception e)
                            {
                            }
                        }
                }
            }


            string[] files = GetFiles(@"" + newPath + "\\AthleteNameAdded");
            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

            foreach (string file in files)
            {
                PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(file, PdfDocumentOpenMode.Import);
                int count = inputDocument.PageCount;
                for (int idx = 0; idx < count; idx++)
                {
                    // Get the page from the external document...
                    PdfSharp.Pdf.PdfPage page = inputDocument.Pages[idx];
                    // ...and add it to the output document.
                    outputDocument.AddPage(page);
                }
            }

            // Save the document...
            string concatenatedFilePath = @"" + desktopPath + "\\PR_Cards\\";

            if (!System.IO.Directory.Exists(concatenatedFilePath))
            {
                System.IO.Directory.CreateDirectory(concatenatedFilePath);
            }
            string concatenatedFileName = concatenatedFilePath + "PR_Cards_For_" + meetInfo[0].Replace(' ', '_') + ".pdf";

            try
            {
                outputDocument.Save(concatenatedFileName);
                // ...and start a viewer.
                Process.Start(concatenatedFileName);
            }
            catch (Exception e3)
            {
                MessageBox.Show("Please close PDF documents.");
            }

            //empty the temporary folder
            Array.ForEach(Directory.GetFiles(@"" + newPath + "\\AthleteNameAdded\\"), File.Delete);
        }
Beispiel #21
0
        private void btn_GenFiles_Click(object sender, EventArgs e)
        {
            c_PositionImages cp     = new c_PositionImages();
            List <Bitmap>    bmplst = cp.createPositions(psl[cb_Scheme.SelectedIndex], picList, selectedDPI);

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (Properties.Settings.Default.s_LastDir != "" && Directory.Exists(Properties.Settings.Default.s_LastDir))
            {
                fbd.SelectedPath = Properties.Settings.Default.s_LastDir;
            }

            fbd.ShowNewFolderButton = true;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                Properties.Settings.Default.s_LastDir = fbd.SelectedPath;
                Properties.Settings.Default.Save();

                string   path = fbd.SelectedPath;
                DateTime d    = DateTime.Now;
                if (rb_PDF.Checked)
                {
                    string fn = "pic_collage_pdf_" + d.Year + d.Month + d.Day + "_" + d.Hour + d.Minute + ".pdf";

                    using (PdfSharp.Pdf.PdfDocument pdoc = new PdfSharp.Pdf.PdfDocument())
                    {
                        pdoc.PageLayout = PdfSharp.Pdf.PdfPageLayout.SinglePage;
                        if (!Directory.Exists(fbd.SelectedPath))
                        {
                            Directory.CreateDirectory(fbd.SelectedPath);
                        }
                        if (!Directory.Exists(fbd.SelectedPath + "\\tmp"))
                        {
                            Directory.CreateDirectory(fbd.SelectedPath + "\\tmp");
                        }
                        foreach (Bitmap b in bmplst)
                        {
                            b.Save(fbd.SelectedPath + "\\tmp\\bmp_tmp_" + bmplst.IndexOf(b) + ".bmp");
                            PdfSharp.Pdf.PdfPage pag = pdoc.AddPage();

                            pag.Width  = selectedDPI.width;
                            pag.Height = selectedDPI.height;
                            XGraphics gfx   = XGraphics.FromPdfPage(pag);
                            XImage    image = XImage.FromFile(fbd.SelectedPath + "\\tmp\\bmp_tmp_" + bmplst.IndexOf(b) + ".bmp");
                            gfx.DrawImage(image, 0, 0, (int)pag.Width, (int)pag.Height);

                            image.Dispose();
                            b.Dispose();
                            gfx.Dispose();
                            pag.Close();
                        }

                        pdoc.Save(fbd.SelectedPath + "\\" + fn);
                    }
                    Directory.Delete(fbd.SelectedPath + "\\tmp", true);
                    System.Diagnostics.Process.Start("explorer.exe", "/select, \"" + fbd.SelectedPath + "\\" + fn + "\"");
                }
                else
                {
                    string fn = "bmp_" + d.Year + d.Month + d.Day + "_" + d.Hour + d.Minute + "_";
                    foreach (Bitmap b in bmplst)
                    {
                        b.Save(fbd.SelectedPath + "\\" + fn + bmplst.IndexOf(b) + ".bmp");
                    }

                    System.Diagnostics.Process.Start("explorer.exe", "/select, \"" + fbd.SelectedPath + "\\" + fn + "0.bmp\"");
                }
            }

            GC.Collect();
        }
Beispiel #22
0
 }//RedimImage
 void AddLogo(XGraphics gfx, PdfSharp.Pdf.PdfPage page, System.Drawing.Image image, int xPosition, int yPosition)
 {
     XImage xImage = XImage.FromGdiPlusImage(image);
     gfx.DrawImage(xImage, xPosition, yPosition);
 }
Beispiel #23
0
 /// <summary>Add a new page if the current page is not empty</summary>
 public void addPage() {
     if (!_isPageEmpty) {
         if (_pageCount != 0)
             addPagenumber();
         _page = new PdfSharp.Pdf.PdfPage();
         if (_pageCount == 0) {
             _size.Width = _page.Width;
             _size.Height = _page.Height;
             _area = new PdfSharp.Drawing.XRect {
                 X = PdfSharp.Drawing.XUnit.FromMillimeter(10),
                 Y = PdfSharp.Drawing.XUnit.FromMillimeter(10),
                 Width = _page.Width - PdfSharp.Drawing.XUnit.FromMillimeter(20),
                 Height = _page.Height - PdfSharp.Drawing.XUnit.FromMillimeter(45)
             };
         } else {
             _page = new PdfSharp.Pdf.PdfPage();
             _page.Width = _size.Width;
             _page.Height = _size.Height;
         }
         _horizontalePosition = _area.X;
         _verticalPosition = _area.Y;
         _doc.AddPage(_page);
         if (_graphics != null)
             _graphics.Dispose();
         _graphics = PdfSharp.Drawing.XGraphics.FromPdfPage(_page);
         _textformater = new PdfSharp.Drawing.Layout.XTextFormatter(_graphics);
         _pageCount++;
         _isPageEmpty = true;
     }
 }
Beispiel #24
0
        private void SaveToPDF(System.Drawing.Image image)
        {       
            string derniereImage; //contient le chemin vers le fax courant (.tif)
            string nomFichier = "Fax_Received_From_" + NumFaxExpediteur + "_Client_ " + NumClient + "_Fax_" + CompteurDeFaxToday; //Nomination de tout les fichiers similaire 
            try
            {
                dernierFax = cheminSauvgardeAnneMois + nomFichier + ".pdf";
                derniereImage = cheminSauvegarde + nomFichier + ".tif";
                NombreDeFax++;
                PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();
                PdfSharp.Pdf.PdfPage page = document.AddPage();
                XGraphics gfx = XGraphics.FromPdfPage(page);
                XFont codeBarre = new XFont("c39hrp24dhtt", 35);
                XFont arial = new XFont("Arial", 10);
                
                AddLogo(gfx, page, RedimImage(image), 20,20);
                string temps = NombreDeFax + "";
                String.Format("{0,20}", temps);

                gfx.DrawString("Exp", arial, XBrushes.Black, new XRect(-270, 380, page.Width, page.Height), XStringFormats.Center);
                gfx.DrawString("*"+NumFaxExpediteur+"*", codeBarre, XBrushes.Black, new XRect(-180, 380, page.Width,page.Height), XStringFormats.Center);
                
                gfx.DrawString("Client", arial, XBrushes.Black, new XRect(-50, 380, page.Width,page.Height), XStringFormats.Center);
                gfx.DrawString("*"+NumClient+"*", codeBarre, XBrushes.Black, new XRect(10, 380, page.Width,page.Height), XStringFormats.Center);

                gfx.DrawString("Fax", arial, XBrushes.Black, new XRect(130, 380, page.Width,page.Height), XStringFormats.Center);
                gfx.DrawString("*"+ temps.PadLeft(7, '0') + "*", codeBarre, XBrushes.Black, new XRect(200, 380, page.Width,page.Height), XStringFormats.Center);

                
                document.Save(dernierFax);
                //Libere les ressources utilisé 
                document.Close();
                document.Dispose();
                ////Information sur l'impression du document

                ProcessStartInfo info = new ProcessStartInfo(dernierFax);
                info.Verb = "Print";
                info.CreateNoWindow = true;
                info.WindowStyle = ProcessWindowStyle.Hidden;
                Process.Start(info);

                //// Récupere la date de l'image une fois traité
                dernierFax = derniereImage;
                dateTraiter = DateTime.Now;

                //Supprime l'image édité une fois l'opération et le PDF terminé
                File.Delete(derniereImage);
                traite = true;
            }
            catch (DocumentException de)
            {
                MessageBox.Show("Impossible de créer le PDF, érreur d'écriture/Lecture");
                Console.Error.WriteLine(de.Message);

            }
            catch (PdfSharp.PdfSharpException ioe)
            {
                MessageBox.Show("Erreur lors de la lecture du document, le fichier est peut être corompue ou inexistant" + ioe);
                Console.Error.WriteLine(ioe.Message);
                traite = false;
            }
        }//SaveToPDF
        private string GenerateLP()
        {
            List <string> fileFragment = new List <string>();
            string        savePath     = "";
            string        filePath     = Server.MapPath("~/Document/Generate/");
            string        qrpath       = Server.MapPath("~/Document/QR/");
            string        qr           = QRcode.GenerateQR(txtNoOrder.Text.Replace(" ", ""), qrpath); //.Replace("/", "")
            string        fileName     = "";
            string        replaceName  = null;

            try
            {
                var ret   = orderControls.GetDataForPrint(txtNoOrder.Text);
                var order = ret.Result;
                replaceName = order.orderNo.Replace("/", "");
                var ordersample = order.ordersampletbls.ToList();
                var orderprice  = order.orderpricedetailtbls;

                SpreadsheetInfo.SetLicense(ConfigurationManager.AppSettings["GemboxLicense"]);
                bool isPackage = false;
                if (order.comoditytbl.isPackage == "1")
                {
                    isPackage = true;
                }
                // Load Excel file.
                var templateName = isPackage ? "/TemplateLP_Paket.xlsx" : "/TemplateLP.xlsx";
                var workbook     = ExcelFile.Load(Server.MapPath("~/Document/Template") + templateName);

                // Select active worksheet.
                var worksheet = workbook.Worksheets[0];

                worksheet.Cells["G9"].Value  = order.orderNo;
                worksheet.Cells["D12"].Value = order.sampleTotal;
                worksheet.Cells["D11"].Value = order.receiptDate;
                worksheet.Cells["F13"].Value = ordersample[0].village;
                worksheet.Cells["L13"].Value = ordersample[0].subDistrict;
                worksheet.Cells["F14"].Value = ordersample[0].district;
                worksheet.Cells["L14"].Value = ordersample[0].province;
                worksheet.Cells["F15"].Value = ordersample[0].longitude + "," + ordersample[0].latitude;
                worksheet.Cells["D16"].Value = order.customertbl.customerName;
                worksheet.Cells["D17"].Value = order.customertbl.companyName;
                worksheet.Cells["D18"].Value = order.customertbl.companyAddress;
                worksheet.Cells["M17"].Value = order.customertbl.companyPhone;
                // Insert Image
                worksheet.Pictures.Add(qr, "A49");
                //worksheet.Pictures.Add(qr, "N8", "N12");

                int     pages          = 1;
                int     startRow       = 22;
                int     row            = 0;
                int     rowLimit       = 21;
                int     totalPage      = decimal.ToInt32(Math.Ceiling(orderprice.Count() / (decimal)21));
                decimal pagetotalprice = 0;

                foreach (var item in orderprice)
                {
                    worksheet.Cells[row + startRow, 0].Value  = row + 1;
                    worksheet.Cells[row + startRow, 1].Value  = item.elementservicestbl.elementCode;
                    worksheet.Cells[row + startRow, 10].Value = item.price.Value <= 0 ? "-" : item.price.Value.ToString("N0");
                    worksheet.Cells[row + startRow, 12].Value = item.quantity;
                    worksheet.Cells[row + startRow, 13].Value = item.TotalPrice.Value <= 0 ? "-" : item.TotalPrice.Value.ToString("N0");

                    pagetotalprice = pagetotalprice + item.TotalPrice.Value;

                    row++;

                    if (row == rowLimit)
                    {
                        worksheet.Cells["N45"].Value = isPackage ? order.priceTotal?.ToString("N0") : pagetotalprice.ToString("N0");
                        worksheet.Cells["N46"].Value = "page" + pages + "/" + totalPage;
                        if (isPackage)
                        {
                            worksheet.Cells["B48"].Value = order.additionalPriceRemark;
                        }
                        // Save the file in PDF format.
                        CheckFolderExists(filePath);
                        fileName = replaceName + "_page" + pages + ".pdf";
                        savePath = filePath + fileName;
                        workbook.Save(savePath);
                        fileFragment.Add(savePath);

                        pages++;

                        for (int x = 1; x < 21; x++)
                        {
                            worksheet.Cells[row + startRow, 0].Value  = "";
                            worksheet.Cells[row + startRow, 1].Value  = "";
                            worksheet.Cells[row + startRow, 10].Value = "";
                            worksheet.Cells[row + startRow, 12].Value = "";
                            worksheet.Cells[row + startRow, 13].Value = "";
                        }
                        row            = 0;
                        pagetotalprice = 0;
                    }
                }

                if (pages > 1)
                {
                    worksheet.Cells["N45"].Value = isPackage ? order.priceTotal?.ToString("N0") : pagetotalprice.ToString("N0");
                    worksheet.Cells["N46"].Value = "page" + pages + "/" + totalPage;
                    if (isPackage)
                    {
                        worksheet.Cells["B48"].Value = order.additionalPriceRemark;
                    }
                    // Save the file in PDF format.
                    CheckFolderExists(filePath);
                    fileName = replaceName + "_page" + pages + ".pdf";
                    savePath = filePath + fileName;
                    fileFragment.Add(savePath);
                    workbook.Save(savePath);

                    #region Combine multiple pdf
                    // Open the output document
                    PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

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

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

                    // Save the document...
                    CheckFolderExists(filePath);
                    fileName = replaceName + ".pdf";
                    savePath = filePath + fileName;
                    outputDocument.Save(savePath);
                    #endregion
                }
                else
                {
                    worksheet.Cells["N45"].Value = isPackage ? order.priceTotal?.ToString("N0") : pagetotalprice.ToString("N0");
                    worksheet.Cells["N46"].Value = "page" + pages + "/" + totalPage;
                    if (isPackage)
                    {
                        worksheet.Cells["B48"].Value = order.additionalPriceRemark;
                    }
                    // Save the file in PDF format.
                    CheckFolderExists(filePath);
                    fileName = replaceName + ".pdf";
                    savePath = filePath + fileName;
                    workbook.Save(savePath);
                }

                return(savePath);
            }
            catch (Exception ex)
            {
            }
            return(null);
        }