예제 #1
0
        /// <summary>
        /// Creates PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //Load a PDF document.
            PdfLoadedDocument document = new PdfLoadedDocument(GetFullTemplatePath("EmpDetails.pdf", false));

            //Get first page from document
            PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;

            //Create PDF redaction for the page to redact text
            PdfRedaction textRedaction = new PdfRedaction(new RectangleF(343, 147, 60, 17), System.Drawing.Color.Black);
            //Create PDF redaction for the page to redact image
            PdfRedaction imageRedaction = new PdfRedaction(new RectangleF(67, 372, 178, 158), System.Drawing.Color.Black);

            //Adds the redactions to loaded page
            page.Redactions.Add(textRedaction);
            page.Redactions.Add(imageRedaction);

            //Save the PDF document
            document.Save("Redacted.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
                Process.Start("Redacted.pdf");
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
예제 #2
0
        /// <summary>
        /// Removes a list of ink annotations from a page.
        /// </summary>
        /// <param name="page">1-based page number.</param>
        /// <param name="inkAnnotations">A list of ink annotations to be removed.
        /// Annotation not found in the page will be ignored.</param>
        /// <returns>If at least one annotation is removed, true. Otherwise false.</returns>
        public bool RemoveInkAnnotations(PdfLoadedPage page, List <PdfInkAnnotation> inkAnnotations)
        {
            bool annotationRemoved = false;
            List <PdfLoadedAnnotation> toBeRemoved = new List <PdfLoadedAnnotation>();

            foreach (PdfLoadedAnnotation annotation in page.Annotations)
            {
                if (annotation is PdfLoadedInkAnnotation loadedInk)
                {
                    PdfInkAnnotation matched = null;
                    foreach (PdfInkAnnotation erasedInk in inkAnnotations)
                    {
                        if (MatchInkAnnotations(loadedInk, erasedInk))
                        {
                            toBeRemoved.Add(annotation);
                            matched = erasedInk;
                            break;
                        }
                    }
                    if (matched != null)
                    {
                        inkAnnotations.Remove(matched);
                    }
                }
            }
            foreach (PdfLoadedAnnotation a in toBeRemoved)
            {
                page.Annotations.Remove(a);
                annotationRemoved = true;
            }
            return(annotationRemoved);
        }
예제 #3
0
        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            string text = textbox.Text;

            // Get the template PDF file stream from assembly.
            Stream documentStream = typeof(FindText).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.pdf_succinctly.pdf");

            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);

            TextSearchResultCollection results;

            //Create list and add a string text to find from PDF document.
            List <string> searchItem = new List <string>();

            searchItem.Add(text);

            //Find text from PDF document and get the result collection.
            loadedDocument.FindText(searchItem, out results);

            //Iterate over the result collection.
            foreach (var result in results)
            {
                //Get the PDF page using the result.
                PdfLoadedPage page = loadedDocument.Pages[result.Key] as PdfLoadedPage;
                //Save the current graphics state.
                page.Graphics.Save();
                //Set transparency to the page graphics.
                page.Graphics.SetTransparency(0.5F);

                foreach (var matchedItem in result.Value)
                {
                    //Draw rectangle to highlight the text in PDF page.
                    page.Graphics.DrawRectangle(PdfBrushes.Yellow, matchedItem.Bounds);
                }
                //Restore the graphics state.
                page.Graphics.Restore();
            }

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("FindText.pdf", stream);
            }
        }
예제 #4
0
        /// <summary>
        /// Splits and creates a new PDF document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSplit_Click(object sender, EventArgs e)
        {
            string dataPath1 = File1.ResolveClientUrl(File1.Value);

            if (System.IO.Path.GetExtension(dataPath1).Equals(".pdf"))
            {
                Stream stream1 = File1.PostedFile.InputStream;

                //Load a PDF document
                PdfLoadedDocument ldoc = new PdfLoadedDocument(stream1);

                //Get first page from document
                PdfLoadedPage lpage = ldoc.Pages[0] as PdfLoadedPage;

                if (x.Text != "" && y.Text != "" && width.Text != "" && height.Text != "")
                {
                    float x1      = float.Parse(x.Text);
                    float y1      = float.Parse(y.Text);
                    float width1  = float.Parse(width.Text);
                    float height1 = float.Parse(height.Text);

                    //Create PDF redaction for the page
                    PdfRedaction redaction = new PdfRedaction(new RectangleF(x1, y1, width1, height1), Color.Black);

                    //Adds the redaction to loaded page
                    lpage.Redactions.Add(redaction);

                    //Save to disk
                    if (this.CheckBox1.Checked)
                    {
                        ldoc.Save("Document1.pdf", Response, HttpReadType.Open);
                    }
                    else
                    {
                        ldoc.Save("Document1.pdf", Response, HttpReadType.Save);
                    }
                }
                else
                {
                    lb_error.Visible = true;
                    lb_error.Text    = "Note: Fill all the fields then redact";
                }
            }
            else
            {
                lb_error.Visible = true;
                lb_error.Text    = "Invalid file type. Please select a PDF file";
            }
        }
예제 #5
0
        public PrintSheet()
        {
            //Create the new document
            document = new PdfDocument();
            document.PageSettings.Orientation = PdfPageOrientation.Landscape;
            document.PageSettings.Margins.All = 0;

            //Load the existing documents
            templatedDocument = new PdfLoadedDocument(@"resources\PrintSheetTemplate.pdf");

            //Create a template from the first document
            PdfLoadedPage loadedPage = templatedDocument.Pages[0] as PdfLoadedPage;

            template = loadedPage.CreateTemplate();
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            //Load an existing PDF.
            PdfLoadedDocument document = new PdfLoadedDocument(this.GetFullTemplatePath(@"Redaction.pdf", false));

            //Get first page from document
            PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;

            //Create PDF redaction for the page to redact text
            PdfRedaction textRedaction = new PdfRedaction(new RectangleF(86.998f, 39.565f, 62.709f, 20.802f), System.Drawing.Color.Black);
            //Create PDF redaction for the page to redact text
            PdfRedaction pathRedaction = new PdfRedaction(new RectangleF(83.7744f, 576.066f, 210.0746f, 104.155f), System.Drawing.Color.Black);
            //Create PDF redaction for the page to redact text
            PdfRedaction imageRedaction = new PdfRedaction(new RectangleF(327.848f, 63.97198f, 232.179f, 223.429f), System.Drawing.Color.Black);

            //Adds the redactions to loaded page
            page.Redactions.Add(textRedaction);
            page.Redactions.Add(pathRedaction);
            page.Redactions.Add(imageRedaction);

            //Save and close the PDF document
            document.Save("Redacted.pdf");
            document.Close(true);

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Redacted.pdf")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                System.Diagnostics.Process.Start("Redacted.pdf");
#endif
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
예제 #7
0
        public PageMapping(Windows.Data.Pdf.PdfPage msPage, PdfLoadedPage sfPage)
        {
            Rotation = (int)msPage.Rotation;
            // The page size returned from Syncfusion pdf is the media box size.
            ScaleRatio = sfPage.Size.Width / msPage.Dimensions.MediaBox.Width;

            // The ink canvas size is the same as crop box
            // Crop box could be smaller than media box
            // There will be an offset if the crop box is smaller than the media box.
            Offset = new Point(
                msPage.Dimensions.CropBox.Left * ScaleRatio,
                msPage.Dimensions.CropBox.Top * ScaleRatio
                );
            PageSize  = new System.Drawing.SizeF(sfPage.Size.Width, sfPage.Size.Height);
            Rectangle = new System.Drawing.RectangleF(0, 0, sfPage.Size.Width, sfPage.Size.Height);
        }
        public ActionResult Redaction(string Browser, string x, string y, string width, string height)
        {
            if (Request.Form.Files != null && Request.Form.Files.Count != 0)
            {
                float x1;
                float y1;
                float width1;
                float height1;
                if (x != null && x.Length > 0 && float.TryParse(x.ToString(), out x1) && y != null && y.Length > 0 && float.TryParse(y.ToString(), out y1) && width != null && width.Length > 0 && float.TryParse(width.ToString(), out width1) && height != null && height.Length > 0 && float.TryParse(height.ToString(), out height1))
                {
                    //Load a PDF document
                    PdfLoadedDocument ldoc = new PdfLoadedDocument(Request.Form.Files[0].OpenReadStream());
                    //Get first page from document
                    PdfLoadedPage lpage = ldoc.Pages[0] as PdfLoadedPage;

                    //Create PDF redaction for the page
                    PdfRedaction redaction = new PdfRedaction(new Syncfusion.Drawing.RectangleF(x1, y1, width1, height1), Syncfusion.Drawing.Color.Black);

                    //Adds the redaction to loaded page
                    lpage.AddRedaction(redaction);
                    ldoc.Redact();
                    //Save the PDF to the MemoryStream
                    MemoryStream ms = new MemoryStream();

                    ldoc.Save(ms);

                    //If the position is not set to '0' then the PDF will be empty.
                    ms.Position = 0;

                    ldoc.Close(true);
                    //Download the PDF document in the browser.
                    FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
                    fileStreamResult.FileDownloadName = "Redaction.pdf";
                    return(fileStreamResult);
                }
                else
                {
                    ViewBag.lab = "Fill proper redaction bounds to redact";
                }
            }
            else
            {
                ViewBag.lab = "Choose PDF document to redact";
            }
            return(View());
        }
예제 #9
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            //Load an existing PDF.
            PdfLoadedDocument document = new PdfLoadedDocument(this.GetFullTemplatePath(@"EmpDetails.pdf", false));

            //Get first page from document
            PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;

            //Create PDF redaction for the page to redact text
            PdfRedaction textRedaction = new PdfRedaction(new RectangleF(343, 147, 60, 17), System.Drawing.Color.Black);
            //Create PDF redaction for the page to redact image
            PdfRedaction imageRedaction = new PdfRedaction(new RectangleF(67, 372, 178, 158), System.Drawing.Color.Black);

            //Adds the redactions to loaded page
            page.Redactions.Add(textRedaction);
            page.Redactions.Add(imageRedaction);

            //Save and close the PDF document
            document.Save("Redacted.pdf");
            document.Close(true);

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Redacted.pdf")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                System.Diagnostics.Process.Start("Redacted.pdf");
#endif
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
예제 #10
0
파일: PdfModel.cs 프로젝트: mpalka/Libra
        /// <summary>
        /// Loads the ink annotations in the PDF file.
        /// </summary>
        /// <param name="pageNumber">1-based page number.</param>
        /// <returns></returns>
        public List <InkStroke> LoadInFileInkAnnotations(int pageNumber)
        {
            List <PdfLoadedInkAnnotation> inkAnnotations = sfPdf.GetInkAnnotations(pageNumber);
            List <InkStroke> strokes = new List <InkStroke>();
            // Get page information from SF model
            PdfLoadedPage sfPage = sfPdf.GetPage(pageNumber);

            // Get page information from MS model
            Windows.Data.Pdf.PdfPage msPage = msPdf.GetPage(pageNumber);
            // Calculate page mapping
            PageMapping mapping = new PageMapping(msPage, sfPage);

            foreach (PdfLoadedInkAnnotation annotation in inkAnnotations)
            {
                strokes.Add(mapping.InkAnnotation2InkStroke(annotation));
            }
            return(strokes);
        }
예제 #11
0
        protected override void Execute(CodeActivityContext context)
        {
            List <string> files          = new List <string>();
            string        filePath       = FilePath.Get(context);
            string        fileFolderPath = Path.GetDirectoryName(filePath);
            // Get current working directory
            string currentDirectory = Directory.GetCurrentDirectory();
            //Load the PDF document
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(filePath);
            //Get first page from document
            PdfLoadedPage page = loadedDocument.Pages[0] as PdfLoadedPage;
            //Get the annotation collection from pages
            PdfLoadedAnnotationCollection annotations = page.Annotations;

            //Iterates the annotations
            foreach (PdfLoadedAnnotation annot in annotations)
            {
                //Check for the attachment annotation
                if (annot is PdfLoadedAttachmentAnnotation)
                {
                    PdfLoadedAttachmentAnnotation file = annot as PdfLoadedAttachmentAnnotation;
                    //Extracts the attachment and saves it to the disk
                    FileStream stream = new FileStream(file.FileName, FileMode.Create);
                    stream.Write(file.Data, 0, file.Data.Length);
                    stream.Dispose();
                }
            }
            //Iterates through the attachments
            if (loadedDocument.Attachments.Count != 0)
            {
                foreach (PdfAttachment attachment in loadedDocument.Attachments)
                {
                    string fullPath = fileFolderPath + "\\" + attachment.FileName;
                    //Extracts the attachment and saves it to the disk
                    FileStream stream = new FileStream(fullPath, FileMode.Create);
                    stream.Write(attachment.Data, 0, attachment.Data.Length);
                    files.Add(fullPath);
                    stream.Dispose();
                }
            }
            //Close the document
            loadedDocument.Close(true);
            Files.Set(context, files);
        }
        public ActionResult Redaction(string Browser, string x, string y, string width, string height, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);

                float x1;
                float y1;
                float width1;
                float height1;
                if (x != null && x.Length > 0 && float.TryParse(x.ToString(), out x1) && y != null && y.Length > 0 && float.TryParse(y.ToString(), out y1) && width != null && width.Length > 0 && float.TryParse(width.ToString(), out width1) && height != null && height.Length > 0 && float.TryParse(height.ToString(), out height1))
                {
                    //Load a PDF document
                    PdfLoadedDocument ldoc = new PdfLoadedDocument(file.InputStream);
                    //Get first page from document
                    PdfLoadedPage lpage = ldoc.Pages[0] as PdfLoadedPage;

                    //Create PDF redaction for the page
                    PdfRedaction redaction = new PdfRedaction(new RectangleF(x1, y1, width1, height1), Color.Black);

                    //Adds the redaction to loaded page
                    lpage.Redactions.Add(redaction);

                    //Save to disk
                    if (Browser == "Browser")
                    {
                        return(ldoc.ExportAsActionResult("Document1.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
                    }
                    else
                    {
                        return(ldoc.ExportAsActionResult("Document1.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
                    }
                }
                else
                {
                    ViewBag.lab = "Fill proper redaction bounds to redact";
                }
            }
            else
            {
                ViewBag.lab = "Choose PDF document to redact";
            }
            return(View());
        }
예제 #13
0
        //---------------------------------------------------------------------------//
        //  Still working on implementation >> the check is not in sync with viewer  //
        //      ** Button and/or button group is therefore curently disabled **      //
        //---------------------------------------------------------------------------//
        private void PopupComment_Click(object sender, RoutedEventArgs e)
        {
            int lastHighlightedPageIndex = 0;
            string selectedText = PdfViewer.SelectedText;
            //Get the whole selected text 

            if (PdfViewer.SelectedText != null)
            {
                foreach (var selectedTextInfo in selectedTextInformation)
                {
                    PdfLoadedPage page = PdfViewer.LoadedDocument.Pages[selectedTextInfo.Key - 1] as PdfLoadedPage;
                    lastHighlightedPageIndex = selectedTextInfo.Key;
                    Dictionary<string, Rectangle> SelectedTexts = selectedTextInfo.Value;
                   
                    foreach (var selectedtext in SelectedTexts)
                    {
                        //Add text markup annotation on the bounds of highlighting text
                        PdfTextMarkupAnnotation textmarkup = new PdfTextMarkupAnnotation(selectedtext.Value)
                        {
                            //Sets the markup annotation type as HighLight
                            TextMarkupAnnotationType = PdfTextMarkupAnnotationType.Highlight,
                            //Sets the content of the annotation
                            Text = selectedText,
                            //Sets the highlighting color
                            TextMarkupColor = new PdfColor(System.Drawing.Color.Yellow)
                        };
                        
                        //Add annotation into page
                        page.Annotations.Add(textmarkup);
                    }
                }

                //Save the document to disk. Save the LoadedDocument and reload into PdfViewerControl
                MemoryStream stream = new MemoryStream
                {
                    Position = 0
                };
                PdfViewer.LoadedDocument.Save(stream);
                PdfViewer.Load(stream);
                PdfViewer.GoToPageAtIndex(lastHighlightedPageIndex);
            }
        }
        private void MergePDFToImg(ref PdfLoadedDocument doc)
        {
            //Get first page from document

            PdfLoadedPage page = doc.Pages[0] as PdfLoadedPage;

            //Create PDF graphics for the page

            PdfGraphics graphics = page.Graphics;

            //Load the image from the disk

            FileStream imageStream = new FileStream(@"XXXXXXX.png", FileMode.Open, FileAccess.Read);

            PdfBitmap image = new PdfBitmap(imageStream);

            //Draw the image

            doc.Pages.Add().Graphics.DrawImage(image, (page.Size.Width / 4), (page.Size.Height / 2) - image.Height, image.Width, image.Height);

            //graphics.DrawImage(image, (page.Size.Width / 4), (page.Size.Height / 2) - image.Height, image.Width, image.Height);
        }
예제 #15
0
        static void Main(string[] args)
        {
            //Load the PDF document
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../../../../../Data/Attachment.pdf");

            //Get first page from document
            PdfLoadedPage page = loadedDocument.Pages[0] as PdfLoadedPage;
            //Get the annotation collection from pages
            PdfLoadedAnnotationCollection annotations = page.Annotations;

            //Iterates the annotations
            foreach (PdfLoadedAnnotation annot in annotations)
            {
                //Check for the attachment annotation
                if (annot is PdfLoadedAttachmentAnnotation)
                {
                    PdfLoadedAttachmentAnnotation file = annot as PdfLoadedAttachmentAnnotation;
                    //Extracts the attachment and saves it to the disk
                    FileStream stream = new FileStream(file.FileName, FileMode.Create);
                    stream.Write(file.Data, 0, file.Data.Length);
                    stream.Dispose();
                }
            }
            //Iterates through the attachments
            if (loadedDocument.Attachments.Count != 0)
            {
                foreach (PdfAttachment attachment in loadedDocument.Attachments)
                {
                    //Extracts the attachment and saves it to the disk
                    FileStream stream = new FileStream(attachment.FileName, FileMode.Create);
                    stream.Write(attachment.Data, 0, attachment.Data.Length);
                    stream.Dispose();
                }
            }
            //Close the document
            loadedDocument.Close(true);
        }
        public ActionResult Redaction(string viewTemplate, string RedactPdf, string Browser, string x, string y, string width, string height, HttpPostedFileBase file)
        {
            if (viewTemplate == "View Template")
            {
                string dataPath = ResolveApplicationDataPath("Redaction.pdf");
                Stream file2    = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                //Load the template document
                PdfLoadedDocument doc = new PdfLoadedDocument(file2);
                return(doc.ExportAsActionResult("RedactionTemplate.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else if (RedactPdf == "Redact PDF")
            {
                string dataPath = ResolveApplicationDataPath("Redaction.pdf");
                Stream file2    = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                //Load the template document
                PdfLoadedDocument doc = new PdfLoadedDocument(file2);

                PdfLoadedPage lpage = doc.Pages[0] as PdfLoadedPage;

                PdfRedaction textRedaction = new PdfRedaction(new RectangleF(86.998f, 39.565f, 62.709f, 20.802f), System.Drawing.Color.Black);
                //Create PDF redaction for the page to redact text
                PdfRedaction pathRedaction = new PdfRedaction(new RectangleF(83.7744f, 576.066f, 210.0746f, 104.155f), System.Drawing.Color.Black);
                //Create PDF redaction for the page to redact text
                PdfRedaction imageRedation = new PdfRedaction(new RectangleF(327.848f, 63.97198f, 232.179f, 223.429f), System.Drawing.Color.Black);

                lpage.Redactions.Add(textRedaction);
                lpage.Redactions.Add(pathRedaction);
                lpage.Redactions.Add(imageRedation);

                return(doc.ExportAsActionResult("Redaction.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
            else
            {
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);

                    float x1;
                    float y1;
                    float width1;
                    float height1;
                    if (x != null && x.Length > 0 && float.TryParse(x.ToString(), out x1) && y != null && y.Length > 0 && float.TryParse(y.ToString(), out y1) && width != null && width.Length > 0 && float.TryParse(width.ToString(), out width1) && height != null && height.Length > 0 && float.TryParse(height.ToString(), out height1))
                    {
                        //Load a PDF document
                        PdfLoadedDocument ldoc = new PdfLoadedDocument(file.InputStream);
                        //Get first page from document
                        PdfLoadedPage lpage = ldoc.Pages[0] as PdfLoadedPage;

                        //Create PDF redaction for the page
                        PdfRedaction redaction = new PdfRedaction(new RectangleF(x1, y1, width1, height1), Color.Black);

                        //Adds the redaction to loaded page
                        lpage.Redactions.Add(redaction);

                        //Save to disk
                        if (Browser == "Browser")
                        {
                            return(ldoc.ExportAsActionResult("Document1.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
                        }
                        else
                        {
                            return(ldoc.ExportAsActionResult("Document1.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
                        }
                    }
                    else
                    {
                        ViewBag.lab = "Fill proper redaction bounds to redact";
                    }
                }
                else
                {
                    ViewBag.lab = "Choose PDF document to redact";
                }
            }
            return(View());
        }
        private static PDFAnnotation ConvertLegacyAnnotationToPDFAnnotation(PDFDocument pdf_document, int page, PdfLoadedPage raw_pdf_page, PdfAnnotation raw_pdf_annotation)
        {
            // Try a popup
            {
                PdfLoadedPopupAnnotation raw_popup_annotation = raw_pdf_annotation as PdfLoadedPopupAnnotation;
                if (null != raw_popup_annotation)
                {
                    Logging.Debug("  - page       = {0}", raw_pdf_page.Size);
                    Logging.Debug("  - annotation = {0}", raw_popup_annotation.Bounds);
                    Logging.Debug("  - text       = {0}", raw_popup_annotation.Text);

                    // Work out the relative coordinates
                    double BUFFER_HORIZ = 0.05;
                    double BUFFER_VERT  = 0.1;
                    double left         = BUFFER_HORIZ;
                    double width        = 1 - 2 * BUFFER_HORIZ;
                    double top          = 1.0 - (raw_popup_annotation.Bounds.Top / raw_pdf_page.Size.Height) - BUFFER_VERT / 2 + (raw_popup_annotation.Bounds.Height / raw_pdf_page.Size.Height) / 2;
                    double height       = BUFFER_VERT;

                    //Bound it
                    top = Math.Max(0, top);

                    string text = raw_popup_annotation.Icon + ": " + raw_popup_annotation.Text;

                    // Create the annotation
                    PDFAnnotation pdf_annotation = new PDFAnnotation(pdf_document.PDFRenderer.DocumentFingerprint, page + 1, PDFAnnotationEditorControl.LastAnnotationColor, null);
                    pdf_annotation.Legacy = true;
                    pdf_annotation.Left   = left;
                    pdf_annotation.Top    = top;
                    pdf_annotation.Width  = width;
                    pdf_annotation.Height = height;
                    pdf_annotation.Text   = text;
                    return(pdf_annotation);
                }
            }

            // Try a highlight
            {
                PdfLoadedTextMarkupAnnotation raw_markup_annotation = raw_pdf_annotation as PdfLoadedTextMarkupAnnotation;
                if (null != raw_markup_annotation)
                {
                    Logging.Debug("  - page       = {0}", raw_pdf_page.Size);
                    Logging.Debug("  - annotation = {0}", raw_markup_annotation.Bounds);

                    // Work out the relative coordinates
                    double left   = raw_markup_annotation.Bounds.Left / raw_pdf_page.Size.Width;
                    double width  = raw_markup_annotation.Bounds.Width / raw_pdf_page.Size.Width;
                    double top    = 1 - (raw_markup_annotation.Bounds.Top / raw_pdf_page.Size.Height);
                    double height = raw_markup_annotation.Bounds.Height / raw_pdf_page.Size.Height;

                    string text = raw_markup_annotation.TextMarkupAnnotationType.ToString();

                    // Create the annotation
                    PDFAnnotation pdf_annotation = new PDFAnnotation(pdf_document.PDFRenderer.DocumentFingerprint, page + 1, PDFAnnotationEditorControl.LastAnnotationColor, null);
                    pdf_annotation.Legacy = true;
                    pdf_annotation.Left   = left;
                    pdf_annotation.Top    = top;
                    pdf_annotation.Width  = width;
                    pdf_annotation.Height = height;
                    pdf_annotation.Text   = text;
                    return(pdf_annotation);
                }
            }

            // We don't understand this annotation
            {
                return(null);
            }
        }
        public static int ImportLegacyAnnotations(PDFDocument pdf_document)
        {
            int imported_count = 0;

            if (!pdf_document.DocumentExists)
            {
                Logging.Info("Not importing legacy annotations for {0} because it has no PDF.", pdf_document.Fingerprint);
                return(imported_count);
            }


            Logging.Info("+Importing legacy annotations from {0}", pdf_document.Fingerprint);
            using (AugmentedPdfLoadedDocument raw_pdf_document = new AugmentedPdfLoadedDocument(pdf_document.PDFRenderer.PDFFilename))
            {
                for (int page = 0; page < raw_pdf_document.Pages.Count; ++page)
                {
                    PdfLoadedPage raw_pdf_page = (PdfLoadedPage)raw_pdf_document.Pages[page];
                    if (null != raw_pdf_page.Annotations)
                    {
                        foreach (PdfAnnotation raw_pdf_annotation in raw_pdf_page.Annotations)
                        {
                            PDFAnnotation pdf_annotation = ConvertLegacyAnnotationToPDFAnnotation(pdf_document, page, raw_pdf_page, raw_pdf_annotation);
                            if (null != pdf_annotation)
                            {
                                // Check if we already have this annotation
                                PDFAnnotation matching_existing_pdf_annotation = null;
                                foreach (PDFAnnotation existing_pdf_annotation in pdf_document.Annotations)
                                {
                                    if (true &&
                                        existing_pdf_annotation.Page == pdf_annotation.Page &&
                                        existing_pdf_annotation.Left == pdf_annotation.Left &&
                                        existing_pdf_annotation.Top == pdf_annotation.Top &&
                                        existing_pdf_annotation.Text == pdf_annotation.Text
                                        )
                                    {
                                        matching_existing_pdf_annotation = existing_pdf_annotation;
                                    }
                                }

                                if (null == matching_existing_pdf_annotation)
                                {
                                    // Add it to the PDFDocument
                                    pdf_document.Annotations.AddUpdatedAnnotation(pdf_annotation);
                                    imported_count++;
                                }
                                else
                                {
                                    if (matching_existing_pdf_annotation.Deleted)
                                    {
                                        Logging.Info("Undeleting an identical legacy annotation.");
                                        matching_existing_pdf_annotation.Deleted = false;
                                        matching_existing_pdf_annotation.Bindable.NotifyPropertyChanged();
                                        imported_count++;
                                    }
                                    else
                                    {
                                        Logging.Info("Not importing an identical legacy annotation.");
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Logging.Info("-Importing legacy annotations from {0}", pdf_document.Fingerprint);

            return(imported_count);
        }
예제 #19
0
        /// <summary>
        /// Gets the number of annotations in a page.
        /// The annotations include not all types of annotations.
        /// </summary>
        /// <param name="pageNumber">1-based page number</param>
        /// <returns>The number of annotations.</returns>
        public int AnnotationCount(int pageNumber)
        {
            PdfLoadedPage loadedPage = GetPage(pageNumber);

            return(loadedPage.Annotations.Count);
        }
예제 #20
0
        public ActionResult AnnotationFlatten(string InsideBrowser, string checkboxFlatten)
        {
            //Creates a new PDF document.
            PdfDocument document = new PdfDocument();

            //Creates a new page
            PdfPage page = document.Pages.Add();

            document.PageSettings.SetMargins(0);

            //Create new PDF color
            PdfColor blackColor = new PdfColor(0, 0, 0);

            RectangleF bounds = new RectangleF(350, 50, 80, 80);
            PdfFont    font   = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            PdfBrush   brush  = new PdfSolidBrush(blackColor);

            //Creates a new Circle annotation.
            PdfCircleAnnotation circleannotation = new PdfCircleAnnotation(bounds);

            circleannotation.InnerColor      = new PdfColor(Color.Yellow);
            circleannotation.Color           = new PdfColor(Color.Red);
            circleannotation.AnnotationFlags = PdfAnnotationFlags.Default;
            circleannotation.Author          = "Syncfusion";
            circleannotation.Subject         = "CircleAnnotation";
            circleannotation.ModifiedDate    = new DateTime(2015, 1, 18);
            page.Annotations.Add(circleannotation);
            page.Graphics.DrawString("Circle Annotation", font, brush, new PointF(350, 10));

            //Creates a new Ellipse annotation.
            PdfEllipseAnnotation ellipseannotation = new PdfEllipseAnnotation(new RectangleF(30, 30, 50, 100), "Ellipse Annotation");

            ellipseannotation.Color      = new PdfColor(Color.Red);
            ellipseannotation.InnerColor = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("Ellipse Annotation", font, brush, new PointF(30, 10));
            page.Annotations.Add(ellipseannotation);

            //Creates a new Square annotation.
            PdfSquareAnnotation squareannotation = new PdfSquareAnnotation(new RectangleF(30, 200, 80, 80));

            squareannotation.Text       = "SquareAnnotation";
            squareannotation.InnerColor = new PdfColor(Color.Red);
            squareannotation.Color      = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("Square Annotation", font, brush, new PointF(30, 180));
            page.Annotations.Add(squareannotation);

            //Creates a new Rectangle annotation.
            RectangleF             rectannot           = new RectangleF(350, 220, 100, 50);
            PdfRectangleAnnotation rectangleannotation = new PdfRectangleAnnotation(rectannot, "RectangleAnnotation");

            rectangleannotation.InnerColor = new PdfColor(Color.Red);
            rectangleannotation.Color      = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("Rectangle Annotation", font, brush, new PointF(350, 180));
            page.Annotations.Add(rectangleannotation);

            //Creates a new Line annotation.
            int[]             points         = new int[] { 400, 450, 550, 450 };
            PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(points, "Line Annoation is the one of the annotation type...");

            lineAnnotation.Author       = "Syncfusion";
            lineAnnotation.Subject      = "LineAnnotation";
            lineAnnotation.ModifiedDate = new DateTime(2015, 1, 18);
            lineAnnotation.Text         = "PdfLineAnnotation";
            lineAnnotation.BackColor    = new PdfColor(Color.Red);
            page.Graphics.DrawString("Line Annotation", font, brush, new PointF(400, 320));
            page.Annotations.Add(lineAnnotation);

            //Creates a new Polygon annotation.
            int[] polypoints = new int[] { 50, 398, 100, 425, 200, 455, 300, 330, 180, 330 };
            PdfPolygonAnnotation polygonannotation = new PdfPolygonAnnotation(polypoints, "PolygonAnnotation");

            polygonannotation.Bounds = new RectangleF(30, 350, 300, 200);
            PdfPen pen = new PdfPen(Color.Red);

            polygonannotation.Text       = "polygon";
            polygonannotation.Color      = new PdfColor(Color.Red);
            polygonannotation.InnerColor = new PdfColor(Color.LightPink);
            page.Graphics.DrawString("Polygon Annotation", font, brush, new PointF(50, 320));
            page.Annotations.Add(polygonannotation);

            //Creates a new Freetext annotation.
            RectangleF            freetextrect = new RectangleF(405, 525, 80, 30);
            PdfFreeTextAnnotation freeText     = new PdfFreeTextAnnotation(freetextrect);

            freeText.MarkupText      = "Free Text with Callouts";
            freeText.TextMarkupColor = new PdfColor(Color.Green);
            freeText.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7f);
            freeText.BorderColor     = new PdfColor(Color.Blue);
            freeText.Border          = new PdfAnnotationBorder(.5f);
            freeText.AnnotationFlags = PdfAnnotationFlags.Default;
            freeText.Text            = "Free Text";
            freeText.Color           = new PdfColor(Color.Yellow);
            PointF[] Freetextpoints = { new PointF(365, 580), new PointF(379, 534), new PointF(405, 534) };
            freeText.CalloutLines = Freetextpoints;
            page.Graphics.DrawString("FreeText Annotation", font, brush, new PointF(400, 510));
            page.Annotations.Add(freeText);

            //Creates a new TextMarkup annotation.
            string     s = "This is TextMarkup annotation!!!";
            RectangleF Textmarkuprect = new RectangleF(30, 540, 200, 20);

            page.Graphics.DrawString(s, font, brush, new PointF(30, 540));
            PdfTextMarkupAnnotation textannot = new PdfTextMarkupAnnotation("sample", "Highlight", s, new PointF(70, 580), font);

            textannot.Author                   = "Annotation";
            textannot.Opacity                  = 1.0f;
            textannot.Subject                  = "pdftextmarkupannotation";
            textannot.ModifiedDate             = new DateTime(2015, 1, 18);
            textannot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.StrikeOut;
            textannot.TextMarkupColor          = new PdfColor(Color.Yellow);
            textannot.InnerColor               = new PdfColor(Color.Red);
            textannot.Color = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("TextMarkup Annotation", font, brush, new PointF(30, 510));
            page.Annotations.Add(textannot);

            //Creates a new Ink annotation.
            List <float> linePoints = new List <float> {
                72.919f, 136.376f, 72.264f, 136.376f, 62.446f, 142.922f, 61.137f, 142.922f, 55.901f, 139.649f, 55.246f, 138.34f, 54.592f, 132.449f, 54.592f, 127.867f, 55.901f, 125.904f, 59.828f, 121.976f, 63.101f, 121.322f, 65.719f, 122.631f, 68.992f, 125.249f, 70.301f, 130.485f, 71.61f, 133.104f, 72.264f, 136.376f, 72.919f, 140.304f, 74.883f, 144.885f, 76.192f, 150.776f, 76.192f, 151.431f, 76.192f, 152.085f, 76.192f, 158.631f, 76.192f, 159.94f, 75.537f, 155.358f, 74.228f, 150.122f, 74.228f, 146.195f, 73.574f, 141.613f, 73.574f, 137.685f, 74.228f, 132.449f, 74.883f, 128.522f, 75.537f, 124.594f, 76.192f, 123.285f, 76.846f, 122.631f, 80.774f, 122.631f, 82.737f, 123.285f, 85.355f, 125.249f, 88.628f, 129.831f, 89.283f, 133.104f, 89.937f, 137.031f, 90.592f, 140.958f, 89.937f, 142.267f, 86.665f, 141.613f, 85.355f, 140.304f, 84.701f, 138.34f, 84.701f, 137.685f, 85.355f, 137.031f, 87.974f, 135.722f, 90.592f, 136.376f, 92.555f, 137.031f, 96.483f, 139.649f, 98.446f, 140.958f, 101.719f, 142.922f, 103.028f, 142.922f, 100.41f, 138.34f, 99.756f, 134.413f, 99.101f, 131.14f, 99.101f, 128.522f, 99.756f, 127.213f, 101.065f, 125.904f, 102.374f, 123.94f, 103.683f, 123.94f, 107.61f, 125.904f, 110.228f, 129.831f, 114.156f, 135.067f, 117.428f, 140.304f, 119.392f, 143.576f, 121.356f, 144.231f, 122.665f, 144.231f, 123.974f, 142.267f, 126.592f, 139.649f, 127.247f, 140.304f, 126.592f, 142.922f, 124.628f, 143.576f, 122.01f, 142.922f, 118.083f, 141.613f, 114.81f, 136.376f, 114.81f, 131.14f, 113.501f, 127.213f, 114.156f, 125.904f, 118.083f, 125.904f, 120.701f, 126.558f, 123.319f, 130.485f, 125.283f, 136.376f, 125.937f, 140.304f, 125.937f, 142.922f, 126.592f, 143.576f, 125.937f, 135.722f, 125.937f, 131.794f, 125.937f, 131.14f, 127.247f, 129.176f, 129.21f, 127.213f, 131.828f, 127.213f, 134.447f, 128.522f, 136.41f, 136.376f, 139.028f, 150.122f, 141.647f, 162.558f, 140.992f, 163.213f, 138.374f, 160.595f, 135.756f, 153.395f, 135.101f, 148.158f, 134.447f, 140.304f, 134.447f, 130.485f, 133.792f, 124.594f, 133.792f, 115.431f, 133.792f, 110.194f, 133.792f, 105.612f, 134.447f, 105.612f, 137.065f, 110.194f, 137.719f, 116.74f, 139.028f, 120.013f, 139.028f, 123.94f, 137.719f, 127.213f, 135.756f, 130.485f, 134.447f, 130.485f, 133.792f, 130.485f, 137.719f, 131.794f, 141.647f, 135.722f, 146.883f, 142.922f, 152.774f, 153.395f, 153.428f, 159.286f, 150.156f, 159.94f, 147.537f, 156.667f, 146.883f, 148.813f, 146.883f, 140.958f, 146.883f, 134.413f, 146.883f, 125.904f, 145.574f, 118.703f, 145.574f, 114.776f, 145.574f, 112.158f, 146.228f, 111.503f, 147.537f, 111.503f, 148.192f, 112.158f, 150.156f, 112.812f, 150.81f, 113.467f, 152.119f, 114.776f, 154.083f, 117.394f, 155.392f, 119.358f, 156.701f, 120.667f, 157.356f, 121.976f, 156.701f, 121.322f, 156.047f, 120.013f, 155.392f, 119.358f, 154.083f, 117.394f, 154.083f, 116.74f, 152.774f, 114.776f, 152.119f, 114.121f, 150.81f, 113.467f, 149.501f, 113.467f, 147.537f, 112.158f, 146.883f, 112.158f, 145.574f, 111.503f, 144.919f, 112.158f, 144.265f, 114.121f, 144.265f, 115.431f, 144.265f, 116.74f, 144.265f, 117.394f, 144.265f, 118.049f, 144.919f, 118.703f, 145.574f, 120.667f, 146.228f, 122.631f, 147.537f, 123.285f, 147.537f, 124.594f, 148.192f, 125.904f, 147.537f, 128.522f, 147.537f, 129.176f, 147.537f, 130.485f, 147.537f, 132.449f, 147.537f, 134.413f, 147.537f, 136.376f, 147.537f, 138.34f, 147.537f, 138.994f, 145.574f, 138.994f, 142.956f, 138.252f
            };
            RectangleF       rectangle     = new RectangleF(30, 580, 300, 400);
            PdfInkAnnotation inkAnnotation = new PdfInkAnnotation(rectangle, linePoints);

            inkAnnotation.Bounds = rectangle;
            inkAnnotation.Color  = new PdfColor(Color.Red);
            page.Graphics.DrawString("Ink Annotation", font, brush, new PointF(30, 610));
            page.Annotations.Add(inkAnnotation);

            //Creates a new popup annotation.
            RectangleF         popupRect       = new RectangleF(430, 670, 30, 30);
            PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation();

            popupAnnotation.Border.Width            = 4;
            popupAnnotation.Border.HorizontalRadius = 20;
            popupAnnotation.Border.VerticalRadius   = 30;
            popupAnnotation.Opacity    = 1;
            popupAnnotation.Open       = true;
            popupAnnotation.Text       = "Popup Annotation";
            popupAnnotation.Color      = Color.Green;
            popupAnnotation.InnerColor = Color.Blue;
            popupAnnotation.Bounds     = popupRect;
            if (checkboxFlatten == "Flatten")
            {
                popupAnnotation.FlattenPopUps = true;
                popupAnnotation.Flatten       = true;
            }
            page.Graphics.DrawString("Popup Annotation", font, brush, new PointF(400, 610));
            page.Annotations.Add(popupAnnotation);

            //Creates a new Line measurement annotation.
            points = new int[] { 400, 350, 550, 350 };
            PdfLineMeasurementAnnotation lineMeasureAnnot = new PdfLineMeasurementAnnotation(points);

            lineMeasureAnnot.Author                 = "Syncfusion";
            lineMeasureAnnot.Subject                = "LineAnnotation";
            lineMeasureAnnot.ModifiedDate           = new DateTime(2015, 1, 18);
            lineMeasureAnnot.Unit                   = PdfMeasurementUnit.Inch;
            lineMeasureAnnot.lineBorder.BorderWidth = 2;
            lineMeasureAnnot.Font                   = new PdfStandardFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular);
            lineMeasureAnnot.Color                  = new PdfColor(Color.Red);
            if (checkboxFlatten == "Flatten")
            {
                lineMeasureAnnot.Flatten = true;
            }
            page.Graphics.DrawString("Line Measurement Annotation", font, brush, new PointF(370, 410));
            page.Annotations.Add(lineMeasureAnnot);

            PdfPage secondPage = document.Pages.Add();
            //Creates a new Freetext annotation.
            RectangleF            freetextrect0 = new RectangleF(80, 130, 100, 50);
            PdfFreeTextAnnotation freeText0     = new PdfFreeTextAnnotation(freetextrect0);

            freeText0.MarkupText      = "Free Text with Callouts";
            freeText0.TextMarkupColor = new PdfColor(Color.Green);
            freeText0.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7f);
            freeText0.BorderColor     = new PdfColor(Color.Blue);
            freeText0.Border          = new PdfAnnotationBorder(.5f);
            freeText0.AnnotationFlags = PdfAnnotationFlags.Default;
            freeText0.Text            = "Free Text";
            freeText0.Rotate          = PdfAnnotationRotateAngle.RotateAngle90;
            freeText0.Color           = new PdfColor(Color.Yellow);
            PointF[] Freetextpoints0 = { new PointF(45, 190), new PointF(60, 145), new PointF(80, 145) };
            freeText0.CalloutLines = Freetextpoints0;
            secondPage.Graphics.DrawString("Rotated FreeText Annotation", font, brush, new PointF(40, 110));
            if (checkboxFlatten == "Flatten")
            {
                freeText0.Flatten = true;
            }
            secondPage.Annotations.Add(freeText0);

            MemoryStream SourceStream = new MemoryStream();

            document.Save(SourceStream);
            document.Close(true);

            //Creates a new Loaded document.
            PdfLoadedDocument lDoc  = new PdfLoadedDocument(SourceStream);
            PdfLoadedPage     lpage = lDoc.Pages[0] as PdfLoadedPage;

            if (checkboxFlatten == "Flatten")
            {
                lpage.Annotations.Flatten = true;
            }

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            lDoc.Save(ms);

            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;

            lDoc.Close(true);

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

            fileStreamResult.FileDownloadName = "Annotation.pdf";
            return(fileStreamResult);
        }
예제 #21
0
파일: PdfModel.cs 프로젝트: mpalka/Libra
        /// <summary>
        /// Save the ink annotations into the pdf file.
        /// </summary>
        /// <param name="inkDictionary"></param>
        /// <returns></returns>
        /// <remarks>
        /// The page size returned from Syncfusion pdf is the media box size.
        /// The page size displayed to the end user is the crop box size.
        /// The size of the ink canvas is the same as the crop box size.
        /// Syncfusion uses the bottom left corner as the origin, while ink canvas uses the top left corner.
        /// </remarks>
        public async Task <bool> SaveInkingToPdf(InkingManager inkManager)
        {
            // Indicate whether any ink annotation is added to the PDF file
            bool fileChanged = false;

            // Remove ereased ink annotations
            foreach (KeyValuePair <int, List <InkStroke> > entry in await inkManager.ErasedStrokesDictionary())
            {
                // The key of the dictionary is page number, which is 1-based.
                int           pageNumber = entry.Key;
                PdfLoadedPage sfPage     = sfPdf.GetPage(pageNumber);
                // Get page information from MS model
                Windows.Data.Pdf.PdfPage msPage = msPdf.GetPage(pageNumber);

                PageMapping             mapping           = new PageMapping(msPage, sfPage);
                List <PdfInkAnnotation> erasedAnnotations = new List <PdfInkAnnotation>();
                // Add each ink stroke to the page
                foreach (InkStroke stroke in entry.Value)
                {
                    PdfInkAnnotation inkAnnotation = mapping.InkStroke2InkAnnotation(stroke);
                    erasedAnnotations.Add(inkAnnotation);
                }
                if (sfPdf.RemoveInkAnnotations(sfPage, erasedAnnotations))
                {
                    fileChanged = true;
                }
            }


            // Add new ink annotations
            foreach (KeyValuePair <int, InkStrokeContainer> entry in await inkManager.InAppInkDictionary())
            {
                PdfLoadedPage sfPage = sfPdf.GetPage(entry.Key);
                // Get page information from MS model
                Windows.Data.Pdf.PdfPage msPage = msPdf.GetPage(entry.Key);

                PageMapping mapping = new PageMapping(msPage, sfPage);

                // Add each ink stroke to the page
                foreach (InkStroke stroke in entry.Value.GetStrokes())
                {
                    PdfInkAnnotation inkAnnotation = mapping.InkStroke2InkAnnotation(stroke);
                    sfPage.Annotations.Add(inkAnnotation);
                    fileChanged = true;
                }
            }

            // Save the file only if there are changes.
            bool inkSaved = false;

            if (fileChanged)
            {
                try
                {
                    inkSaved = await sfPdf.SaveAsync();

                    // Copy and replace the actual file
                    await sfFile.CopyAndReplaceAsync(pdfFile);
                }
                catch (Exception ex)
                {
                    // Try to save the file by extracting the pages.
                    StorageFile newFile = await backupFolder.CreateFileAsync("COPY_" + pdfFile.Name, CreationCollisionOption.GenerateUniqueName);

                    try
                    {
                        await sfPdf.CopyPages(newFile);

                        inkSaved = true;
                        // Copy and replace the actual file
                        await newFile.CopyAndReplaceAsync(pdfFile);
                    }
                    catch
                    {
                        App.NotifyUser(typeof(ViewerPage), "Error: \n" + ex.Message, true);
                    }
                }
            }
            return(!(inkSaved ^ fileChanged));
        }
예제 #22
0
        static void Main()
        {
            var currentMonthStr = DateTime.Now.ToString("MM");

            if (!int.TryParse(currentMonthStr, out int currentMonth))
            {
                Console.WriteLine($"Erro ao converter mês corrente para inteiro. Mês: {currentMonthStr}");
                goto Finish;
            }

            var yearStr = DateTime.Now.ToString("yyyy");

            if (!int.TryParse(yearStr, out int serviceYear))
            {
                Console.WriteLine($"Erro ao converter ano corrente para inteiro. Ano: {yearStr}");
                goto Finish;
            }

            if (currentMonth >= 9)
            {
                serviceYear = serviceYear + 1;
            }

            var pathRelatorios = Path.Combine(Directory.GetCurrentDirectory(), "Relatorios");

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

            var filename = Directory.GetFiles(pathRelatorios).FirstOrDefault(file => file.EndsWith(".xml"));

            if (filename == null)
            {
                Console.WriteLine("Não existe nenhum ficheiro XML na pasta Relatorios!");
                goto Finish;
            }

            var currentDirectory = Directory.GetCurrentDirectory();
            var doc = Path.Combine(currentDirectory, filename);

            XElement root = XElement.Load(doc);

            IEnumerable <XElement> pubs = from el in root.Elements("Active").Elements("Pub")
                                          select el;

            if (!int.TryParse((string)root.Element("Count"), out int totalPub))
            {
                Console.WriteLine("Número de Publicadores Activos no xml não é um inteiro válido.");
                goto Finish;
            }

            Console.WriteLine("Publicadores Activos: " + totalPub);

            string folderName = "Export-" + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss");

            Directory.CreateDirectory(folderName);

            int index = 1;

            foreach (XElement el in pubs)
            {
                FileStream file;
                try
                {
                    file = new FileStream("S-21-TPO.pdf", FileMode.Open);
                } catch (FileNotFoundException)
                {
                    Console.WriteLine("Coloque o PDF S-21 na pasta do executável, com o nome: S-21-TPO.pdf");
                    goto Finish;
                }
                //Load the PDF document
                PdfLoadedDocument loadedDocument = new PdfLoadedDocument(file);

                ////Gets the first page of the document
                PdfLoadedPage page = loadedDocument.Pages[0] as PdfLoadedPage;

                ////Get the loaded form
                PdfLoadedForm form = loadedDocument.Form;

                // Print Fields' Names

                //foreach (PdfLoadedField field in form.Fields)
                //{
                //    Console.WriteLine(field.Name);
                //}

                var pubName = (string)el.Element("fname") + " " + (string)el.Element("lname");

                Console.WriteLine($"A preencher: {pubName} ({index++}/{totalPub})");

                var publisherType = FillForm(form, el, serviceYear.ToString(), 2);
                FillForm(form, el, (serviceYear - 1).ToString(), 1);

                string subfolder = "Outros";

                switch (publisherType)
                {
                case PublisherType.RegularPioneer:
                    subfolder = "Pioneiros Regulares";
                    break;

                case PublisherType.NonBaptized:
                    subfolder = "Publicadores Não Batizados";
                    break;

                case PublisherType.Baptized:
                    subfolder = $"Grupo {(string)el.Element("group")}";
                    break;
                }

                SaveFile(loadedDocument, folderName, subfolder, pubName);
            }

            Console.WriteLine("Sucesso!");

Finish:
            Console.WriteLine("Click em Enter para terminar...");
            Console.ReadLine();
        }
예제 #23
0
        /// <summary>
        /// Gets a page object from the file.
        /// </summary>
        /// <param name="pageNumber">1-based page number.</param>
        /// <returns></returns>
        public PdfLoadedPage GetPage(int pageNumber)
        {
            PdfLoadedPage page = PdfDoc.Pages[pageNumber - 1] as PdfLoadedPage;

            return(page);
        }
예제 #24
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document
            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.Pages.Add();

            document.PageSettings.SetMargins(0);

            RectangleF bounds = new RectangleF(350, 50, 80, 80);
            PdfFont    font   = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            PdfBrush   brush  = new PdfSolidBrush(System.Drawing.Color.FromArgb(255, 0, 0, 0));
            PdfColor   yellow = new PdfColor(System.Drawing.Color.FromArgb(255, 255, 255, 0));
            PdfColor   red    = new PdfColor(System.Drawing.Color.FromArgb(255, 255, 0, 0));
            PdfColor   green  = new PdfColor(System.Drawing.Color.FromArgb(255, 0, 255, 0));
            PdfColor   blue   = new PdfColor(System.Drawing.Color.FromArgb(255, 0, 0, 255));

            //Creating circle annotation
            PdfCircleAnnotation circleannotation = new PdfCircleAnnotation(bounds);

            circleannotation.InnerColor      = yellow;
            circleannotation.Color           = red;
            circleannotation.AnnotationFlags = PdfAnnotationFlags.Default;
            circleannotation.Author          = "Syncfusion";
            circleannotation.Subject         = "CircleAnnotation";
            circleannotation.ModifiedDate    = new DateTime(2015, 1, 18);
            page.Annotations.Add(circleannotation);
            page.Graphics.DrawString("Circle Annotation", font, brush, new PointF(350, 10));

            //Creating ellipse annotation
            PdfEllipseAnnotation ellipseannotation = new PdfEllipseAnnotation(new RectangleF(30, 30, 50, 100), "Ellipse Annotation");

            ellipseannotation.Color      = yellow;
            ellipseannotation.InnerColor = red;
            page.Graphics.DrawString("Ellipse Annotation", font, brush, new PointF(30, 10));
            page.Annotations.Add(ellipseannotation);

            //Creating square annotation
            PdfSquareAnnotation squareannotation = new PdfSquareAnnotation(new RectangleF(30, 200, 80, 80));

            squareannotation.Text       = "SquareAnnotation";
            squareannotation.InnerColor = red;
            squareannotation.Color      = yellow;
            page.Graphics.DrawString("Square Annotation", font, brush, new PointF(30, 180));
            page.Annotations.Add(squareannotation);

            //Creating rectangle annotation
            RectangleF             rectangle1          = new RectangleF(350, 220, 100, 50);
            PdfRectangleAnnotation rectangleannotation = new PdfRectangleAnnotation(rectangle1, "RectangleAnnotation");

            rectangleannotation.InnerColor = red;
            rectangleannotation.Color      = yellow;
            page.Graphics.DrawString("Rectangle Annotation", font, brush, new PointF(350, 180));
            page.Annotations.Add(rectangleannotation);

            //Creating line annotation
            int[]             points         = new int[] { 400, 450, 550, 450 };
            PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(points, "Line Annoation is the one of the annotation type...");

            lineAnnotation.Author       = "Syncfusion";
            lineAnnotation.Subject      = "LineAnnotation";
            lineAnnotation.ModifiedDate = new DateTime(2015, 1, 18);
            lineAnnotation.Text         = "PdfLineAnnotation";
            lineAnnotation.BackColor    = red;
            page.Graphics.DrawString("Line Annotation", font, brush, new PointF(400, 320));
            page.Annotations.Add(lineAnnotation);

            //Creating polygon annotation
            int[] points1 = new int[] { 50, 398, 100, 425, 200, 455, 300, 330, 180, 330 };
            PdfPolygonAnnotation polygonannotation = new PdfPolygonAnnotation(points1, "Polygon Annotation");

            polygonannotation.Bounds = new RectangleF(30, 350, 300, 200);
            PdfPen pen = new PdfPen(System.Drawing.Color.FromArgb(255, 255, 0, 0));

            polygonannotation.Text       = "polygon";
            polygonannotation.Color      = red;
            polygonannotation.InnerColor = yellow;
            page.Graphics.DrawString("PolygonAnnotation", font, brush, new PointF(50, 320));
            page.Annotations.Add(polygonannotation);


            //Creating text markup annotation
            string     s = "This is TextMarkup annotation!!!";
            RectangleF Textmarkuprect = new RectangleF(30, 540, 200, 20);

            page.Graphics.DrawString(s, font, brush, new PointF(30, 540));
            PdfTextMarkupAnnotation textannot = new PdfTextMarkupAnnotation("sample", "Highlight", s, new PointF(70, 580), font);

            textannot.Author                   = "Annotation";
            textannot.Opacity                  = 1.0f;
            textannot.Subject                  = "pdftextmarkupannotation";
            textannot.ModifiedDate             = new DateTime(2015, 1, 18);
            textannot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.StrikeOut;
            textannot.TextMarkupColor          = yellow;
            textannot.InnerColor               = red;
            textannot.Color = yellow;
            page.Graphics.DrawString("Text Markup Annotation", font, brush, new PointF(30, 510));
            page.Annotations.Add(textannot);

            //Creates a new Ink annotation.
            float[]          inkPoints     = new float[] { 72.919f, 136.376f, 72.264f, 136.376f, 62.446f, 142.922f, 61.137f, 142.922f, 55.901f, 139.649f, 55.246f, 138.34f, 54.592f, 132.449f, 54.592f, 127.867f, 55.901f, 125.904f, 59.828f, 121.976f, 63.101f, 121.322f, 65.719f, 122.631f, 68.992f, 125.249f, 70.301f, 130.485f, 71.61f, 133.104f, 72.264f, 136.376f, 72.919f, 140.304f, 74.883f, 144.885f, 76.192f, 150.776f, 76.192f, 151.431f, 76.192f, 152.085f, 76.192f, 158.631f, 76.192f, 159.94f, 75.537f, 155.358f, 74.228f, 150.122f, 74.228f, 146.195f, 73.574f, 141.613f, 73.574f, 137.685f, 74.228f, 132.449f, 74.883f, 128.522f, 75.537f, 124.594f, 76.192f, 123.285f, 76.846f, 122.631f, 80.774f, 122.631f, 82.737f, 123.285f, 85.355f, 125.249f, 88.628f, 129.831f, 89.283f, 133.104f, 89.937f, 137.031f, 90.592f, 140.958f, 89.937f, 142.267f, 86.665f, 141.613f, 85.355f, 140.304f, 84.701f, 138.34f, 84.701f, 137.685f, 85.355f, 137.031f, 87.974f, 135.722f, 90.592f, 136.376f, 92.555f, 137.031f, 96.483f, 139.649f, 98.446f, 140.958f, 101.719f, 142.922f, 103.028f, 142.922f, 100.41f, 138.34f, 99.756f, 134.413f, 99.101f, 131.14f, 99.101f, 128.522f, 99.756f, 127.213f, 101.065f, 125.904f, 102.374f, 123.94f, 103.683f, 123.94f, 107.61f, 125.904f, 110.228f, 129.831f, 114.156f, 135.067f, 117.428f, 140.304f, 119.392f, 143.576f, 121.356f, 144.231f, 122.665f, 144.231f, 123.974f, 142.267f, 126.592f, 139.649f, 127.247f, 140.304f, 126.592f, 142.922f, 124.628f, 143.576f, 122.01f, 142.922f, 118.083f, 141.613f, 114.81f, 136.376f, 114.81f, 131.14f, 113.501f, 127.213f, 114.156f, 125.904f, 118.083f, 125.904f, 120.701f, 126.558f, 123.319f, 130.485f, 125.283f, 136.376f, 125.937f, 140.304f, 125.937f, 142.922f, 126.592f, 143.576f, 125.937f, 135.722f, 125.937f, 131.794f, 125.937f, 131.14f, 127.247f, 129.176f, 129.21f, 127.213f, 131.828f, 127.213f, 134.447f, 128.522f, 136.41f, 136.376f, 139.028f, 150.122f, 141.647f, 162.558f, 140.992f, 163.213f, 138.374f, 160.595f, 135.756f, 153.395f, 135.101f, 148.158f, 134.447f, 140.304f, 134.447f, 130.485f, 133.792f, 124.594f, 133.792f, 115.431f, 133.792f, 110.194f, 133.792f, 105.612f, 134.447f, 105.612f, 137.065f, 110.194f, 137.719f, 116.74f, 139.028f, 120.013f, 139.028f, 123.94f, 137.719f, 127.213f, 135.756f, 130.485f, 134.447f, 130.485f, 133.792f, 130.485f, 137.719f, 131.794f, 141.647f, 135.722f, 146.883f, 142.922f, 152.774f, 153.395f, 153.428f, 159.286f, 150.156f, 159.94f, 147.537f, 156.667f, 146.883f, 148.813f, 146.883f, 140.958f, 146.883f, 134.413f, 146.883f, 125.904f, 145.574f, 118.703f, 145.574f, 114.776f, 145.574f, 112.158f, 146.228f, 111.503f, 147.537f, 111.503f, 148.192f, 112.158f, 150.156f, 112.812f, 150.81f, 113.467f, 152.119f, 114.776f, 154.083f, 117.394f, 155.392f, 119.358f, 156.701f, 120.667f, 157.356f, 121.976f, 156.701f, 121.322f, 156.047f, 120.013f, 155.392f, 119.358f, 154.083f, 117.394f, 154.083f, 116.74f, 152.774f, 114.776f, 152.119f, 114.121f, 150.81f, 113.467f, 149.501f, 113.467f, 147.537f, 112.158f, 146.883f, 112.158f, 145.574f, 111.503f, 144.919f, 112.158f, 144.265f, 114.121f, 144.265f, 115.431f, 144.265f, 116.74f, 144.265f, 117.394f, 144.265f, 118.049f, 144.919f, 118.703f, 145.574f, 120.667f, 146.228f, 122.631f, 147.537f, 123.285f, 147.537f, 124.594f, 148.192f, 125.904f, 147.537f, 128.522f, 147.537f, 129.176f, 147.537f, 130.485f, 147.537f, 132.449f, 147.537f, 134.413f, 147.537f, 136.376f, 147.537f, 138.34f, 147.537f, 138.994f, 145.574f, 138.994f, 142.956f, 138.252f };
            List <float>     linePoints    = new List <float>(inkPoints);
            RectangleF       rectangle     = new RectangleF(30, 580, 300, 400);
            PdfInkAnnotation inkAnnotation = new PdfInkAnnotation(rectangle, linePoints);

            inkAnnotation.Bounds = rectangle;
            inkAnnotation.Color  = red;
            page.Graphics.DrawString("Ink Annotation", font, brush, new PointF(30, 610));
            page.Annotations.Add(inkAnnotation);

            //Creates a new popup annotation.
            RectangleF         popupRect       = new RectangleF(430, 670, 30, 30);
            PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation();

            popupAnnotation.Border.Width            = 4;
            popupAnnotation.Border.HorizontalRadius = 20;
            popupAnnotation.Border.VerticalRadius   = 30;
            popupAnnotation.Opacity    = 1;
            popupAnnotation.Open       = true;
            popupAnnotation.Text       = "Popup Annotation";
            popupAnnotation.Color      = green;
            popupAnnotation.InnerColor = blue;
            popupAnnotation.Bounds     = popupRect;
            if (flatten.IsChecked == true)
            {
                popupAnnotation.FlattenPopUps = true;
                popupAnnotation.Flatten       = true;
            }
            page.Graphics.DrawString("Popup Annotation", font, brush, new PointF(410, 610));
            page.Annotations.Add(popupAnnotation);

            //Saving the document
            MemoryStream SourceStream = new MemoryStream();

            document.Save(SourceStream);
            document.Close(true);

            //Loading and flatten the  annotation
            PdfLoadedDocument lDoc  = new PdfLoadedDocument(SourceStream);
            PdfLoadedPage     lpage = lDoc.Pages[0] as PdfLoadedPage;

            if (flatten.IsChecked == true)
            {
                lpage.Annotations.Flatten = true;
            }
            MemoryStream stream = new MemoryStream();
            await lDoc.SaveAsync(stream);

            lDoc.Close(true);

            Save(stream, "Sample.pdf");
        }
예제 #25
0
        public string SaveRightMovePdf(RightMoveModel rightMoveModel)
        {
            try
            {
                PdfLoadedDocument loadedDocument = new PdfLoadedDocument(new FileStream(templatePath, FileMode.Open));

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

                if (loadedDocument.PageCount > 0)
                {
                    PdfLoadedPage pdfLoadedPage = loadedDocument.Pages[1] as PdfLoadedPage;

                    PdfTemplate pdfTemplate = new PdfTemplate(900, 600);

                    PdfFont pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 15);

                    PdfBrush brush = new PdfSolidBrush(SfDrawing.Color.Black);

                    byte[] imageBytes  = new WebClient().DownloadData(rightMoveModel.PropertyMainPicture);
                    Stream imageStream = new MemoryStream(imageBytes);

                    pdfTemplate.Graphics.DrawString($"Property Address: {rightMoveModel.PropertyAddress}", pdfFont, brush, 100, 30);
                    pdfTemplate.Graphics.DrawString($"Property Type: {rightMoveModel.PropertyType}", pdfFont, brush, 100, 50);
                    pdfTemplate.Graphics.DrawString($"PropertyPrice: {rightMoveModel.PropertyPrice} ", pdfFont, brush, 100, 70);
                    pdfTemplate.Graphics.DrawImage(PdfImage.FromStream(imageStream), new SfDrawing.PointF(100, 100), new SfDrawing.SizeF(400, 400));

                    pdfLoadedPage.Graphics.DrawPdfTemplate(pdfTemplate, SfDrawing.PointF.Empty);

                    string rawName = rightMoveModel
                                     .PropertyUrl
                                     .Replace("/", "")
                                     .Replace("-", "")
                                     .Replace(".", "")
                                     .Replace(":", "")
                                     .Replace("//", "");

                    string fileName = Regex.Match(rawName, @"(\d+(?:\.\d{1,2})?)").Value;

                    PdfDocument propertyHeatMapPdfDocument = htmlConverter.Convert(rightMoveModel.PropertyHeatHtmlString, string.Empty);
                    PdfDocument homeCoUKHtmlPdfDocument    = htmlConverter.Convert(rightMoveModel.HomeCoUKHtmlString, string.Empty);

                    string tempPropertyHeatMap = Path.Combine(tempFolder, $"propertyHeatMap{fileName}.pdf");

                    using (FileStream propertyHeatMapStream = new FileStream(tempPropertyHeatMap, FileMode.Create))
                    {
                        propertyHeatMapPdfDocument.Save(propertyHeatMapStream);
                        propertyHeatMapPdfDocument.Close(true);
                        propertyHeatMapPdfDocument.Dispose();

                        propertyHeatMapStream.Close();
                        propertyHeatMapStream.Dispose();
                    }

                    string tempHomeCoUK = Path.Combine(tempFolder, $"homeCoUK{fileName}.pdf");

                    using (FileStream homeCoUKHtmlPdfStream = new FileStream(tempHomeCoUK, FileMode.Create))
                    {
                        homeCoUKHtmlPdfDocument.Save(homeCoUKHtmlPdfStream);
                        homeCoUKHtmlPdfDocument.Close(true);
                        homeCoUKHtmlPdfDocument.Dispose();

                        homeCoUKHtmlPdfStream.Close();
                        homeCoUKHtmlPdfStream.Dispose();
                    }

                    using (FileStream propertyHeatMapReadStream = new FileStream(tempPropertyHeatMap, FileMode.Open))
                    {
                        PdfLoadedDocument tempPropertyHeatMapDocument = new PdfLoadedDocument(propertyHeatMapReadStream);
                        loadedDocument.ImportPage(tempPropertyHeatMapDocument, 0);

                        propertyHeatMapReadStream.Close();
                        propertyHeatMapReadStream.Dispose();
                    }

                    using (FileStream homeCoUKReadStream = new FileStream(tempHomeCoUK, FileMode.Open))
                    {
                        PdfLoadedDocument tempHomeCoUKDocument = new PdfLoadedDocument(homeCoUKReadStream);

                        loadedDocument.ImportPage(tempHomeCoUKDocument, 0);

                        homeCoUKReadStream.Close();
                        homeCoUKReadStream.Dispose();
                    }

                    string savePath = Path.Combine(archiveFolder, $"{fileName}.pdf");

                    using (FileStream saveStream = new FileStream(savePath, FileMode.Create))
                    {
                        loadedDocument.Save(saveStream);
                        loadedDocument.Close(true);
                        loadedDocument.Dispose();
                        saveStream.Close();
                        saveStream.Dispose();
                    }

                    return($"file successfully saved at: {savePath}");
                }
                else
                {
                    Console.WriteLine("Invalid PDF file");
                    return($"Invalid PDF file");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unable to save the file. {ex.Message}");

                return($"Unable to save the file");
            }
        }
        public ActionResult Redaction(string viewTemplate, string RedactPdf, string Browser, string x, string y, string width, string height)
        {
            if (viewTemplate == "View Template")
            {
                string basePath = _hostingEnvironment.WebRootPath;
                string dataPath = string.Empty;
                dataPath = basePath + @"/PDF/";

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

                //Load the template document
                PdfLoadedDocument doc = new PdfLoadedDocument(file);

                //Save the PDF to the MemoryStream
                MemoryStream ms = new MemoryStream();
                doc.Save(ms);

                //If the position is not set to '0' then the PDF will be empty.
                ms.Position = 0;

                //Close the PDF document.
                doc.Close(true);

                //Download the PDF document in the browser.
                FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
                fileStreamResult.FileDownloadName = "RedactionTemplate.pdf";
                return(fileStreamResult);
            }
            else if (RedactPdf == "Redact PDF")
            {
                string basePath = _hostingEnvironment.WebRootPath;
                string dataPath = string.Empty;
                dataPath = basePath + @"/PDF/";

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

                //Load the template document
                PdfLoadedDocument doc = new PdfLoadedDocument(file);

                PdfLoadedPage lpage = doc.Pages[0] as PdfLoadedPage;

                PdfRedaction textRedaction = new PdfRedaction(new Syncfusion.Drawing.RectangleF(86.998f, 39.565f, 62.709f, 20.802f), Syncfusion.Drawing.Color.Black);
                //Create PDF redaction for the page to redact text
                PdfRedaction pathRedaction = new PdfRedaction(new Syncfusion.Drawing.RectangleF(83.7744f, 576.066f, 210.0746f, 104.155f), Syncfusion.Drawing.Color.Black);
                //Create PDF redaction for the page to redact text
                PdfRedaction imageRedation = new PdfRedaction(new Syncfusion.Drawing.RectangleF(327.848f, 63.97198f, 232.179f, 223.429f), Syncfusion.Drawing.Color.Black);

                lpage.AddRedaction(textRedaction);
                lpage.AddRedaction(pathRedaction);
                lpage.AddRedaction(imageRedation);

                doc.Redact();
                //Save the PDF to the MemoryStream
                MemoryStream ms = new MemoryStream();
                doc.Save(ms);

                //If the position is not set to '0' then the PDF will be empty.
                ms.Position = 0;

                //Close the PDF document.
                doc.Close(true);

                //Download the PDF document in the browser.
                FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
                fileStreamResult.FileDownloadName = "Redaction.pdf";
                return(fileStreamResult);
            }
            else
            {
                if (Request.Form.Files != null && Request.Form.Files.Count != 0 && viewTemplate != "View Template")
                {
                    float x1;
                    float y1;
                    float width1;
                    float height1;
                    if (x != null && x.Length > 0 && float.TryParse(x.ToString(), out x1) && y != null && y.Length > 0 && float.TryParse(y.ToString(), out y1) && width != null && width.Length > 0 && float.TryParse(width.ToString(), out width1) && height != null && height.Length > 0 && float.TryParse(height.ToString(), out height1))
                    {
                        //Load a PDF document
                        PdfLoadedDocument ldoc = new PdfLoadedDocument(Request.Form.Files[0].OpenReadStream());
                        //Get first page from document
                        PdfLoadedPage lpage = ldoc.Pages[0] as PdfLoadedPage;

                        //Create PDF redaction for the page
                        PdfRedaction redaction = new PdfRedaction(new Syncfusion.Drawing.RectangleF(x1, y1, width1, height1), Syncfusion.Drawing.Color.Black);

                        //Adds the redaction to loaded page
                        lpage.AddRedaction(redaction);
                        ldoc.Redact();
                        //Save the PDF to the MemoryStream
                        MemoryStream ms = new MemoryStream();

                        ldoc.Save(ms);

                        //If the position is not set to '0' then the PDF will be empty.
                        ms.Position = 0;

                        ldoc.Close(true);
                        //Download the PDF document in the browser.
                        FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
                        fileStreamResult.FileDownloadName = "Redaction.pdf";
                        return(fileStreamResult);
                    }
                    else
                    {
                        ViewBag.lab = "Fill proper redaction bounds to redact";
                    }
                }
                else
                {
                    ViewBag.lab = "Choose PDF document to redact";
                }
            }
            return(View());
        }
예제 #27
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document
            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.Pages.Add();

            document.PageSettings.SetMargins(0);

            PdfFont  font  = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            PdfBrush brush = new PdfSolidBrush(System.Drawing.Color.FromArgb(255, 0, 0, 0));
            string   text  = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base.";

            page.Graphics.DrawString("Annotation with Comments and Reviews", font, brush, new PointF(30, 10));
            page.Graphics.DrawString(text, font, brush, new RectangleF(30, 40, page.GetClientSize().Width - 60, 60));

            string markupText = "North American, European and Asian commercial markets";
            PdfTextMarkupAnnotation textMarkupAnnot = new PdfTextMarkupAnnotation("sample", "Highlight", markupText, new PointF(147, 63.5f), font);

            textMarkupAnnot.Author                   = "Annotation";
            textMarkupAnnot.Opacity                  = 1.0f;
            textMarkupAnnot.Subject                  = "Comments and Reviews";
            textMarkupAnnot.ModifiedDate             = new DateTime(2015, 1, 18);
            textMarkupAnnot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.Highlight;
            textMarkupAnnot.TextMarkupColor          = new PdfColor(System.Drawing.Color.Yellow);
            textMarkupAnnot.InnerColor               = new PdfColor(System.Drawing.Color.Red);
            textMarkupAnnot.Color = new PdfColor(System.Drawing.Color.Yellow);
            if (flatten.IsChecked == true)
            {
                textMarkupAnnot.Flatten = true;
            }
            //Create a new comment.
            PdfPopupAnnotation userQuery = new PdfPopupAnnotation();

            userQuery.Author       = "John";
            userQuery.Text         = "Can you please change South Asian to Asian?";
            userQuery.ModifiedDate = new DateTime(2015, 1, 18);
            //Add comment to the annotation
            textMarkupAnnot.Comments.Add(userQuery);

            //Creates a new comment
            PdfPopupAnnotation userAnswer = new PdfPopupAnnotation();

            userAnswer.Author       = "Smith";
            userAnswer.Text         = "South Asian has changed as Asian";
            userAnswer.ModifiedDate = new DateTime(2015, 1, 18);
            //Add comment to the annotation
            textMarkupAnnot.Comments.Add(userAnswer);

            //Creates a new review
            PdfPopupAnnotation userAnswerReview = new PdfPopupAnnotation();

            userAnswerReview.Author       = "Smith";
            userAnswerReview.State        = PdfAnnotationState.Completed;
            userAnswerReview.StateModel   = PdfAnnotationStateModel.Review;
            userAnswerReview.ModifiedDate = new DateTime(2015, 1, 18);
            //Add review to the comment
            userAnswer.ReviewHistory.Add(userAnswerReview);

            //Creates a new review
            PdfPopupAnnotation userAnswerReviewJohn = new PdfPopupAnnotation();

            userAnswerReviewJohn.Author       = "John";
            userAnswerReviewJohn.State        = PdfAnnotationState.Accepted;
            userAnswerReviewJohn.StateModel   = PdfAnnotationStateModel.Review;
            userAnswerReviewJohn.ModifiedDate = new DateTime(2015, 1, 18);
            //Add review to the comment
            userAnswer.ReviewHistory.Add(userAnswerReviewJohn);

            //Add annotation to the page
            page.Annotations.Add(textMarkupAnnot);

            RectangleF bounds = new RectangleF(350, 170, 80, 80);

            //Creates a new Circle annotation.
            PdfCircleAnnotation circleannotation = new PdfCircleAnnotation(bounds);

            circleannotation.InnerColor      = new PdfColor(System.Drawing.Color.Yellow);
            circleannotation.Color           = new PdfColor(System.Drawing.Color.Red);
            circleannotation.AnnotationFlags = PdfAnnotationFlags.Default;
            circleannotation.Author          = "Syncfusion";
            circleannotation.Subject         = "CircleAnnotation";
            circleannotation.ModifiedDate    = new DateTime(2015, 1, 18);
            page.Annotations.Add(circleannotation);
            page.Graphics.DrawString("Circle Annotation", font, brush, new PointF(350, 130));


            //Creates a new Ellipse annotation.
            PdfEllipseAnnotation ellipseannotation = new PdfEllipseAnnotation(new RectangleF(30, 150, 50, 100), "Ellipse Annotation");

            ellipseannotation.Color      = new PdfColor(System.Drawing.Color.Red);
            ellipseannotation.InnerColor = new PdfColor(System.Drawing.Color.Yellow);
            page.Graphics.DrawString("Ellipse Annotation", font, brush, new PointF(30, 130));
            page.Annotations.Add(ellipseannotation);

            //Creates a new Square annotation.
            PdfSquareAnnotation squareannotation = new PdfSquareAnnotation(new RectangleF(30, 300, 80, 80));

            squareannotation.Text       = "SquareAnnotation";
            squareannotation.InnerColor = new PdfColor(System.Drawing.Color.Red);
            squareannotation.Color      = new PdfColor(System.Drawing.Color.Yellow);
            page.Graphics.DrawString("Square Annotation", font, brush, new PointF(30, 280));
            page.Annotations.Add(squareannotation);

            //Creates a new Rectangle annotation.
            RectangleF             rectannot           = new RectangleF(350, 320, 100, 50);
            PdfRectangleAnnotation rectangleannotation = new PdfRectangleAnnotation(rectannot, "RectangleAnnotation");

            rectangleannotation.InnerColor = new PdfColor(System.Drawing.Color.Red);
            rectangleannotation.Color      = new PdfColor(System.Drawing.Color.Yellow);
            page.Graphics.DrawString("Rectangle Annotation", font, brush, new PointF(350, 280));
            page.Annotations.Add(rectangleannotation);

            //Creates a new Line annotation.
            int[]             points         = new int[] { 400, 350, 550, 350 };
            PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(points, "Line Annoation is the one of the annotation type...");

            lineAnnotation.Author       = "Syncfusion";
            lineAnnotation.Subject      = "LineAnnotation";
            lineAnnotation.ModifiedDate = new DateTime(2015, 1, 18);
            lineAnnotation.Text         = "PdfLineAnnotation";
            lineAnnotation.BackColor    = new PdfColor(System.Drawing.Color.Red);
            page.Graphics.DrawString("Line Annotation", font, brush, new PointF(400, 420));
            page.Annotations.Add(lineAnnotation);

            //Creates a new Polygon annotation.
            int[] polypoints = new int[] { 50, 298, 100, 325, 200, 355, 300, 230, 180, 230 };
            PdfPolygonAnnotation polygonannotation = new PdfPolygonAnnotation(polypoints, "PolygonAnnotation");

            polygonannotation.Bounds = new RectangleF(30, 210, 300, 200);
            PdfPen pen = new PdfPen(System.Drawing.Color.Red);

            polygonannotation.Text       = "polygon";
            polygonannotation.Color      = new PdfColor(System.Drawing.Color.Red);
            polygonannotation.InnerColor = new PdfColor(System.Drawing.Color.LightPink);
            page.Graphics.DrawString("Polygon Annotation", font, brush, new PointF(50, 420));
            page.Annotations.Add(polygonannotation);

            //Creates a new Freetext annotation.
            RectangleF            freetextrect = new RectangleF(405, 645, 80, 30);
            PdfFreeTextAnnotation freeText     = new PdfFreeTextAnnotation(freetextrect);

            freeText.MarkupText      = "Free Text with Callouts";
            freeText.TextMarkupColor = new PdfColor(System.Drawing.Color.Green);
            freeText.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7f);
            freeText.BorderColor     = new PdfColor(System.Drawing.Color.Blue);
            freeText.Border          = new PdfAnnotationBorder(.5f);
            freeText.AnnotationFlags = PdfAnnotationFlags.Default;
            freeText.Text            = "Free Text";
            freeText.Color           = new PdfColor(System.Drawing.Color.Yellow);
            PointF[] Freetextpoints = { new PointF(365, 700), new PointF(379, 654), new PointF(405, 654) };
            freeText.CalloutLines = Freetextpoints;
            page.Graphics.DrawString("FreeText Annotation", font, brush, new PointF(400, 610));
            page.Annotations.Add(freeText);

            //Creates a new Ink annotation.
            List <float> linePoints = new List <float> {
                72.919f, 136.376f, 72.264f, 136.376f, 62.446f, 142.922f, 61.137f, 142.922f, 55.901f, 139.649f, 55.246f, 138.34f, 54.592f, 132.449f, 54.592f, 127.867f, 55.901f, 125.904f, 59.828f, 121.976f, 63.101f, 121.322f, 65.719f, 122.631f, 68.992f, 125.249f, 70.301f, 130.485f, 71.61f, 133.104f, 72.264f, 136.376f, 72.919f, 140.304f, 74.883f, 144.885f, 76.192f, 150.776f, 76.192f, 151.431f, 76.192f, 152.085f, 76.192f, 158.631f, 76.192f, 159.94f, 75.537f, 155.358f, 74.228f, 150.122f, 74.228f, 146.195f, 73.574f, 141.613f, 73.574f, 137.685f, 74.228f, 132.449f, 74.883f, 128.522f, 75.537f, 124.594f, 76.192f, 123.285f, 76.846f, 122.631f, 80.774f, 122.631f, 82.737f, 123.285f, 85.355f, 125.249f, 88.628f, 129.831f, 89.283f, 133.104f, 89.937f, 137.031f, 90.592f, 140.958f, 89.937f, 142.267f, 86.665f, 141.613f, 85.355f, 140.304f, 84.701f, 138.34f, 84.701f, 137.685f, 85.355f, 137.031f, 87.974f, 135.722f, 90.592f, 136.376f, 92.555f, 137.031f, 96.483f, 139.649f, 98.446f, 140.958f, 101.719f, 142.922f, 103.028f, 142.922f, 100.41f, 138.34f, 99.756f, 134.413f, 99.101f, 131.14f, 99.101f, 128.522f, 99.756f, 127.213f, 101.065f, 125.904f, 102.374f, 123.94f, 103.683f, 123.94f, 107.61f, 125.904f, 110.228f, 129.831f, 114.156f, 135.067f, 117.428f, 140.304f, 119.392f, 143.576f, 121.356f, 144.231f, 122.665f, 144.231f, 123.974f, 142.267f, 126.592f, 139.649f, 127.247f, 140.304f, 126.592f, 142.922f, 124.628f, 143.576f, 122.01f, 142.922f, 118.083f, 141.613f, 114.81f, 136.376f, 114.81f, 131.14f, 113.501f, 127.213f, 114.156f, 125.904f, 118.083f, 125.904f, 120.701f, 126.558f, 123.319f, 130.485f, 125.283f, 136.376f, 125.937f, 140.304f, 125.937f, 142.922f, 126.592f, 143.576f, 125.937f, 135.722f, 125.937f, 131.794f, 125.937f, 131.14f, 127.247f, 129.176f, 129.21f, 127.213f, 131.828f, 127.213f, 134.447f, 128.522f, 136.41f, 136.376f, 139.028f, 150.122f, 141.647f, 162.558f, 140.992f, 163.213f, 138.374f, 160.595f, 135.756f, 153.395f, 135.101f, 148.158f, 134.447f, 140.304f, 134.447f, 130.485f, 133.792f, 124.594f, 133.792f, 115.431f, 133.792f, 110.194f, 133.792f, 105.612f, 134.447f, 105.612f, 137.065f, 110.194f, 137.719f, 116.74f, 139.028f, 120.013f, 139.028f, 123.94f, 137.719f, 127.213f, 135.756f, 130.485f, 134.447f, 130.485f, 133.792f, 130.485f, 137.719f, 131.794f, 141.647f, 135.722f, 146.883f, 142.922f, 152.774f, 153.395f, 153.428f, 159.286f, 150.156f, 159.94f, 147.537f, 156.667f, 146.883f, 148.813f, 146.883f, 140.958f, 146.883f, 134.413f, 146.883f, 125.904f, 145.574f, 118.703f, 145.574f, 114.776f, 145.574f, 112.158f, 146.228f, 111.503f, 147.537f, 111.503f, 148.192f, 112.158f, 150.156f, 112.812f, 150.81f, 113.467f, 152.119f, 114.776f, 154.083f, 117.394f, 155.392f, 119.358f, 156.701f, 120.667f, 157.356f, 121.976f, 156.701f, 121.322f, 156.047f, 120.013f, 155.392f, 119.358f, 154.083f, 117.394f, 154.083f, 116.74f, 152.774f, 114.776f, 152.119f, 114.121f, 150.81f, 113.467f, 149.501f, 113.467f, 147.537f, 112.158f, 146.883f, 112.158f, 145.574f, 111.503f, 144.919f, 112.158f, 144.265f, 114.121f, 144.265f, 115.431f, 144.265f, 116.74f, 144.265f, 117.394f, 144.265f, 118.049f, 144.919f, 118.703f, 145.574f, 120.667f, 146.228f, 122.631f, 147.537f, 123.285f, 147.537f, 124.594f, 148.192f, 125.904f, 147.537f, 128.522f, 147.537f, 129.176f, 147.537f, 130.485f, 147.537f, 132.449f, 147.537f, 134.413f, 147.537f, 136.376f, 147.537f, 138.34f, 147.537f, 138.994f, 145.574f, 138.994f, 142.956f, 138.252f
            };
            RectangleF       rectangle     = new RectangleF(30, 580, 300, 400);
            PdfInkAnnotation inkAnnotation = new PdfInkAnnotation(rectangle, linePoints);

            inkAnnotation.Bounds = rectangle;
            inkAnnotation.Color  = new PdfColor(System.Drawing.Color.Red);
            page.Graphics.DrawString("Ink Annotation", font, brush, new PointF(30, 610));
            page.Annotations.Add(inkAnnotation);

            PdfPage secondPage = document.Pages.Add();


            //Creates a new TextMarkup annotation.
            string s = "This is TextMarkup annotation!!!";

            secondPage.Graphics.DrawString(s, font, brush, new PointF(30, 70));
            PdfTextMarkupAnnotation textannot = new PdfTextMarkupAnnotation("sample", "Strikeout", s, new PointF(30, 70), font);

            textannot.Author                   = "Annotation";
            textannot.Opacity                  = 1.0f;
            textannot.Subject                  = "pdftextmarkupannotation";
            textannot.ModifiedDate             = new DateTime(2015, 1, 18);
            textannot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.StrikeOut;
            textannot.TextMarkupColor          = new PdfColor(System.Drawing.Color.Yellow);
            textannot.InnerColor               = new PdfColor(System.Drawing.Color.Red);
            textannot.Color = new PdfColor(System.Drawing.Color.Yellow);
            if (flatten.IsChecked == true)
            {
                textannot.Flatten = true;
            }
            secondPage.Graphics.DrawString("TextMarkup Annotation", font, brush, new PointF(30, 40));
            secondPage.Annotations.Add(textannot);

            //Creates a new popup annotation.
            RectangleF         popupRect       = new RectangleF(430, 70, 30, 30);
            PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation();

            popupAnnotation.Border.Width            = 4;
            popupAnnotation.Border.HorizontalRadius = 20;
            popupAnnotation.Border.VerticalRadius   = 30;
            popupAnnotation.Opacity    = 1;
            popupAnnotation.Open       = true;
            popupAnnotation.Text       = "Popup Annotation";
            popupAnnotation.Color      = System.Drawing.Color.Green;
            popupAnnotation.InnerColor = System.Drawing.Color.Blue;
            popupAnnotation.Bounds     = popupRect;
            if (flatten.IsChecked == true)
            {
                popupAnnotation.FlattenPopUps = true;
                popupAnnotation.Flatten       = true;
            }
            secondPage.Graphics.DrawString("Popup Annotation", font, brush, new PointF(400, 40));
            secondPage.Annotations.Add(popupAnnotation);

            //Creates a new Line measurement annotation.
            points = new int[] { 400, 630, 550, 630 };
            PdfLineMeasurementAnnotation lineMeasureAnnot = new PdfLineMeasurementAnnotation(points);

            lineMeasureAnnot.Author                 = "Syncfusion";
            lineMeasureAnnot.Subject                = "LineAnnotation";
            lineMeasureAnnot.ModifiedDate           = new DateTime(2015, 1, 18);
            lineMeasureAnnot.Unit                   = PdfMeasurementUnit.Inch;
            lineMeasureAnnot.lineBorder.BorderWidth = 2;
            lineMeasureAnnot.Font                   = new PdfStandardFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular);
            lineMeasureAnnot.Color                  = new PdfColor(System.Drawing.Color.Red);
            if (flatten.IsChecked == true)
            {
                lineMeasureAnnot.Flatten = true;
            }
            secondPage.Graphics.DrawString("Line Measurement Annotation", font, brush, new PointF(370, 130));
            secondPage.Annotations.Add(lineMeasureAnnot);

            //Creates a new Freetext annotation.
            RectangleF            freetextrect0 = new RectangleF(80, 160, 100, 50);
            PdfFreeTextAnnotation freeText0     = new PdfFreeTextAnnotation(freetextrect0);

            freeText0.MarkupText      = "Free Text with Callouts";
            freeText0.TextMarkupColor = new PdfColor(System.Drawing.Color.Green);
            freeText0.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7f);
            freeText0.BorderColor     = new PdfColor(System.Drawing.Color.Blue);
            freeText0.Border          = new PdfAnnotationBorder(.5f);
            freeText0.AnnotationFlags = PdfAnnotationFlags.Default;
            freeText0.Text            = "Free Text";
            freeText0.Rotate          = PdfAnnotationRotateAngle.RotateAngle90;
            freeText0.Color           = new PdfColor(System.Drawing.Color.Yellow);
            PointF[] Freetextpoints0 = { new PointF(45, 220), new PointF(60, 175), new PointF(80, 175) };
            freeText0.CalloutLines = Freetextpoints0;
            secondPage.Graphics.DrawString("Rotated FreeText Annotation", font, brush, new PointF(40, 130));
            if (flatten.IsChecked == true)
            {
                freeText0.Flatten = true;
            }
            secondPage.Annotations.Add(freeText0);

            PdfRectangleAnnotation cloudannotation = new PdfRectangleAnnotation(new RectangleF(30, 300, 100, 50), "Rectangle Cloud Annoatation");

            cloudannotation.Border.BorderWidth = 1;
            cloudannotation.Color      = System.Drawing.Color.Red;
            cloudannotation.InnerColor = System.Drawing.Color.Blue;
            PdfBorderEffect bordereffect = new PdfBorderEffect();

            bordereffect.Intensity       = 2;
            bordereffect.Style           = PdfBorderEffectStyle.Cloudy;
            cloudannotation.BorderEffect = bordereffect;
            secondPage.Graphics.DrawString("Cloud Annotation", font, brush, new PointF(40, 260));
            secondPage.Annotations.Add(cloudannotation);
            if (flatten.IsChecked == false)
            {
                PdfRedactionAnnotation redactionannot = new PdfRedactionAnnotation();
                redactionannot.Bounds        = new RectangleF(350, 300, 100, 50);
                redactionannot.Text          = "Redaction Annotation";
                redactionannot.InnerColor    = System.Drawing.Color.Orange;
                redactionannot.BorderColor   = System.Drawing.Color.Red;
                redactionannot.Font          = new PdfStandardFont(PdfFontFamily.Helvetica, 13);
                redactionannot.TextColor     = System.Drawing.Color.Green;
                redactionannot.OverlayText   = "REDACTED";
                redactionannot.RepeatText    = true;
                redactionannot.TextAlignment = PdfTextAlignment.Left;
                redactionannot.SetAppearance(true);
                secondPage.Graphics.DrawString("Redaction Annotation", font, brush, new PointF(350, 260));
                secondPage.Annotations.Add(redactionannot);
            }
            //Saving the document
            MemoryStream SourceStream = new MemoryStream();

            document.Save(SourceStream);
            document.Close(true);

            //Loading and flatten the  annotation
            PdfLoadedDocument lDoc   = new PdfLoadedDocument(SourceStream);
            PdfLoadedPage     lpage1 = lDoc.Pages[0] as PdfLoadedPage;
            PdfLoadedPage     lpage2 = lDoc.Pages[1] as PdfLoadedPage;

            if (flatten.IsChecked == true)
            {
                lpage1.Annotations.Flatten = true;
                lpage2.Annotations.Flatten = true;
            }
            MemoryStream stream = new MemoryStream();
            await lDoc.SaveAsync(stream);

            lDoc.Close(true);

            Save(stream, "Sample.pdf");
        }
예제 #28
0
        private void luoLaskuBtn_Click(object sender, EventArgs e)
        {
            bool voikoLuoda = true;
            //Luodaan asiakas ja laitetaan asiakkaalle tiedot
            Asiakas asiakas = new Asiakas();

            asiakas.Sukunimi = sukunimiCBox.Text;
            asiakas.Etunimi  = etunimiCBox.Text;
            asiakas          = handler.HaeAsiakasNimellä(asiakas);

            //Luodaan yritys ja haetaan sille tiedot
            Yritys yritys = new Yritys();

            yritys = handler.HaeYritys(id);


            DateTime dateAndTime = DateTime.Now;
            DateTime eräpäivä    = dateAndTime.AddDays(14);

            //Luodaan lasku ja laitetaan laskulle tiedot
            Lasku lasku = new Lasku();
            int   laskunID;

            lasku.Päivämäärä = dateAndTime;
            lasku.Eräpäivä   = eräpäivä;
            lasku.AsiakasID  = asiakas.Id;
            try
            {
                lasku.Laskutuskausi = laskutusCbox.SelectedItem.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("Et valinnut laskutuskautta", "!Huom");
                voikoLuoda = false;
            }

            if (voikoLuoda == true)
            {
                laskunID = handler.TallennaLasku(lasku);

                string viitenumero;
                viitenumero = Viitenumero(asiakas, laskunID);

                // luodaan pdf tiedosto ja sille olennaiset ominaisuudet
                PdfLoadedDocument loadedDocument = new PdfLoadedDocument(Properties.Resources.laskupohja);
                PdfLoadedForm     loadedForm     = loadedDocument.Form;
                PdfLoadedPage     loadedPage     = loadedDocument.Pages[0] as PdfLoadedPage;
                PdfTemplate       template       = loadedPage.CreateTemplate();
                PdfDocument       document       = new PdfDocument();
                document.PageSettings.SetMargins(2);
                PdfPage     page     = document.Pages.Add();
                PdfGraphics graphics = page.Graphics;
                graphics.DrawPdfTemplate(template, PointF.Empty, new SizeF(page.Size.Width, page.Size.Height));
                PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

                float veroYhteensä, määrä, verotonHinta, hinta, yhteensä;

                float.TryParse(hintaTbox.Text, out hinta);
                float.TryParse(määräTbox.Text, out määrä);
                verotonHinta = hinta * määrä;
                veroYhteensä = verotonHinta * 1.24f - verotonHinta;
                yhteensä     = verotonHinta + veroYhteensä;

                //Viedään tietoa dokumenttiin
                (loadedForm.Fields[0] as PdfLoadedTextBoxField).Text  = dateAndTime.ToString("dd/MM/yyyy");
                (loadedForm.Fields[1] as PdfLoadedTextBoxField).Text  = "7%";                            //Viivästyskorko
                (loadedForm.Fields[2] as PdfLoadedTextBoxField).Text  = laskunID.ToString();             //Laskunumero
                (loadedForm.Fields[3] as PdfLoadedTextBoxField).Text  = asiakas.YTunnus;                 // Asiakkaan Y-Tunnus
                (loadedForm.Fields[4] as PdfLoadedTextBoxField).Text  = maksuehtoTbox.Text;              // Maksuehto
                (loadedForm.Fields[5] as PdfLoadedTextBoxField).Text  = "";                              // Viitteemme
                (loadedForm.Fields[6] as PdfLoadedTextBoxField).Text  = eräpäivä.ToString("dd/MM/yyyy"); // Eräpäivä
                (loadedForm.Fields[7] as PdfLoadedTextBoxField).Text  = "";                              // Viittenne
                (loadedForm.Fields[8] as PdfLoadedTextBoxField).Text  = toimitusehtoTbox.Text;           // Toimitusehto
                (loadedForm.Fields[63] as PdfLoadedTextBoxField).Text = verotonHinta.ToString();         // Veroton yhteensä
                (loadedForm.Fields[64] as PdfLoadedTextBoxField).Text = veroYhteensä.ToString();         // ALV yhteensä
                (loadedForm.Fields[65] as PdfLoadedTextBoxField).Text = yhteensä.ToString();             // Verollinen yhteensä
                (loadedForm.Fields[70] as PdfLoadedTextBoxField).Text = yhteensä.ToString();             // Yhteensä
                (loadedForm.Fields[71] as PdfLoadedTextBoxField).Text = EtunimiLbl.Text + " "
                                                                        + sukunimiLbl.Text + "\n" + osoiteLbl.Text + "\n" + postinumeroLbl.Text + " "
                                                                        + postitoimipaikkaLbl.Text;                      // Asiakkaan tiedot
                (loadedForm.Fields[68] as PdfLoadedTextBoxField).Text = eräpäivä.ToString("dd/MM/yyyy");                 // Eräpäivä
                (loadedForm.Fields[75] as PdfLoadedTextBoxField).Text = yritys.Nimi + "\n" + yritys.Osoite + "\n"        // Laskun lähettäjän tiedot
                                                                        + yritys.Postinumero + " " + yritys.Postiosoite; // Laskun lähettäjän tiedot
                (loadedForm.Fields[66] as PdfLoadedTextBoxField).Text = yritys.Iban;                                     // IBAN
                (loadedForm.Fields[67] as PdfLoadedTextBoxField).Text = yritys.Bicswift;                                 // BIC/SWIFT = 67
                (loadedForm.Fields[69] as PdfLoadedTextBoxField).Text = viitenumero;                                     // Viitenumero = 69
                (loadedForm.Fields[9] as PdfLoadedTextBoxField).Text  = nimikeTbox.Text;                                 // Nimike
                (loadedForm.Fields[10] as PdfLoadedTextBoxField).Text = määräTbox.Text;                                  // Määrä
                (loadedForm.Fields[11] as PdfLoadedTextBoxField).Text = "kpl";                                           // Yks.
                (loadedForm.Fields[12] as PdfLoadedTextBoxField).Text = hintaTbox.Text;                                  // hinta
                (loadedForm.Fields[13] as PdfLoadedTextBoxField).Text = "24%";                                           // Alv %
                (loadedForm.Fields[14] as PdfLoadedTextBoxField).Text = yhteensä.ToString();                             // Verollinen yhteensä

                //Tällä luupilla voi katsoa missä kohdassa mikäkin field on.
                //for (int i = 0; i < 76; i++)
                //{
                //    (loadedForm.Fields[i] as PdfLoadedTextBoxField).Text = i.ToString();
                //}

                // tallenetaan dokumentti
                loadedDocument.Save("Lasku.pdf");
                document.Save("UusiLasku.pdf");
                loadedDocument.Close(true);
                document.Close(true);
                Process.Start("Lasku.pdf");

                // Tarkistetaan onko laskun tiedot saatu tallennettua
                if (laskunID != 0)
                {
                    MessageBox.Show("Laskun tiedot tallennettiin tietokantaan", "Huom");
                }
                else
                {
                    MessageBox.Show("Laskun tietoja ei saatu tallennettua", "Huom");
                }
            }
        }
예제 #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="bodyHtml"></param>
        /// <param name="headerHtml"></param>
        /// <param name="footerHtml"></param>
        /// <param name="headerHeight"></param>
        /// <param name="footerHeight"></param>
        /// <param name="firstPageHeader"></param>
        /// <returns></returns>
        public static string HtmlToPdf(string filePath, string bodyHtml, string headerHtml, string footerHtml, int headerHeight = 96, int footerHeight = 96, bool firstPageHeader = false)
        {
            string css  = "";
            string html = "";

            using (System.IO.StreamReader r = new System.IO.StreamReader(System.Web.Hosting.HostingEnvironment.MapPath(cssPath)))
            {
                css = r.ReadToEnd();
            }
            using (System.IO.StreamReader r = new System.IO.StreamReader(System.Web.Hosting.HostingEnvironment.MapPath(emptyLayoutPath)))
            {
                html = r.ReadToEnd().Replace("[[CSS]]", css);
            }

            PdfDocument document = new PdfDocument();

            document.PageSettings.Size = PdfPageSize.A4;
            document.PageSettings.SetMargins(0);


            //Initialize HTML to PDF converter
            var htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
            //Create new settings
            var setting   = CreateConverterSetting();
            var pdfHeader = HeaderHTMLtoPDF(html.Replace("[[HTML]]", headerHtml), headerHeight);
            var pdfFooter = FooterHTMLtoPDF(html.Replace("[[HTML]]", footerHtml), footerHeight);

            setting.PdfPageSize = new SizeF(PdfPageSize.A4.Width, PdfPageSize.A4.Height - pdfHeader.Height - pdfFooter.Height);

            htmlConverter.ConverterSettings = setting;
            //Convert to PDF
            var         body    = html.Replace("[[HTML]]", bodyHtml);
            PdfDocument docBody = htmlConverter.Convert(body, string.Empty);
            Stream      stream  = new MemoryStream();

            docBody.Save(stream);
            docBody.Close();
            PdfLoadedDocument pdfLoadedDocument = new PdfLoadedDocument(stream);

            for (int i = 0; i < pdfLoadedDocument.Pages.Count; i++)
            {
                PdfLoadedPage loadedPage = pdfLoadedDocument.Pages[i] as PdfLoadedPage;
                PdfTemplate   template   = loadedPage.CreateTemplate();
                PdfSection    section    = document.Sections.Add();
                PdfPage       page       = section.Pages.Add();
                PdfGraphics   graphics   = page.Graphics;
                if (i == 0)
                {
                    section.Template.Top    = pdfHeader;
                    section.Template.Bottom = FooterHTMLtoPDF(html.Replace("[[HTML]]", footerHtml?.Replace("[[Page]]", "1")?.Replace("[[TotalPage]]", pdfLoadedDocument.Pages.Count.ToString())), footerHeight);
                }
                else
                {
                    if (firstPageHeader)
                    {
                        section.Template.Top = HeaderHTMLtoPDF(html.Replace("[[HTML]]", string.Empty), headerHeight);
                    }
                    else
                    {
                        section.Template.Top = HeaderHTMLtoPDF(html.Replace("[[HTML]]", headerHtml), headerHeight);
                    }
                    section.Template.Bottom = FooterHTMLtoPDF(html.Replace("[[HTML]]", footerHtml?.Replace("[[Page]]", (i + 1).ToString())?.Replace("[[TotalPage]]", pdfLoadedDocument.Pages.Count.ToString())), footerHeight);
                }
                graphics.DrawPdfTemplate(template, new PointF(0, pdfHeader.Height), new SizeF(page.Size.Width, page.Size.Height - pdfHeader.Height - pdfFooter.Height));
            }

            //Save the document
            document.Save(filePath);
            document.Close();
            stream.Dispose();
            filePath = filePath.Replace("~", "");
            return(filePath);
        }