Пример #1
0
        public byte[] GenerateHTML(string html)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                PdfWriter   writer = new PdfWriter(ms);//@"D:\Docs\demp.pdf"
                PdfDocument pdfDoc = new PdfDocument(writer);

                // Set the result to be tagged
                pdfDoc.SetTagged();
                pdfDoc.SetDefaultPageSize(PageSize.A4);

                ConverterProperties converterProperties = new ConverterProperties();

                // Set media device description details
                MediaDeviceDescription mediaDescription = new MediaDeviceDescription(MediaType.SCREEN);
                //mediaDescription.SetWidth(screenWidth);
                converterProperties.SetMediaDeviceDescription(mediaDescription);

                FontProvider fp = new DefaultFontProvider();

                // Register external font directory
                ////fp.AddDirectory(resourceLoc);

                ////converterProperties.SetFontProvider(fp);
                // Base URI is required to resolve the path to source files
                ////converterProperties.SetBaseUri(resourceLoc);

                // Create acroforms from text and button input fields
                converterProperties.SetCreateAcroForm(true);

                // HtmlConverter.ConvertToPdf(html, pdfDoc, converterProperties);
                HtmlConverter.ConvertToPdf(html, pdfDoc, converterProperties);

                pdfDoc.Close();
                return(ms.ToArray());
            }
        }
Пример #2
0
        /// <summary>
        /// Convierte texto html de entrada en un archivo pdf.
        /// </summary>
        /// <param name="html">Html a convertir en pdf.</param>
        /// <param name="orientation">Orientación.</param>
        /// <param name="fontData">Byte content of the font program file.</param>
        /// <returns>Datos binarios del pdf.</returns>
        public byte[] GetPdfFormHtml(string html,
                                     string orientation = "PORTRAIT", byte[] fontData = null)
        {
            QRCodeTagWorkerFactory = new QRCodeTagWorkerFactory();

            ConverterProperties properties = new ConverterProperties();

            properties.SetTagWorkerFactory(QRCodeTagWorkerFactory);
            properties.SetCssApplierFactory(new QRCodeTagCssApplierFactory());

            if (fontData != null)
            {
                FontProvider fontProvider = new FontProvider();
                fontProvider.AddFont(fontData, PdfEncodings.IDENTITY_H);

                properties.SetFontProvider(fontProvider);
            }

            byte[] result = null;

            using (var ms = new MemoryStream())
            {
                using (var pdfDocument = new PdfDocument(new PdfWriter(ms)))
                {
                    if (orientation.ToUpper() == "LANDSCAPE")
                    {
                        pdfDocument.SetDefaultPageSize(PageSize.A4.Rotate());
                    }

                    HtmlConverter.ConvertToPdf(html, pdfDocument, properties);
                    result = ms.ToArray();
                }
            }

            return(result);
        }
Пример #3
0
        public FileResult M15()
        {
            var client = new WebClient();

            client.Encoding = Encoding.UTF8;
            var p = MvcHelpers.RenderViewToString(this.ControllerContext, "M15View", db.Orders.First());

            var workStream = new MemoryStream();

            using (var writer = new PdfWriter(workStream))
            {
                PdfDocument pdf = new PdfDocument(writer);
                pdf.SetTagged();
                PageSize pageSize = PageSize.A4.Rotate();
                pageSize.IncreaseHeight(4);
                pdf.SetDefaultPageSize(pageSize);
                ConverterProperties properties = new ConverterProperties();
                properties.SetMediaDeviceDescription(new MediaDeviceDescription(MediaType.PRINT));
                writer.SetCloseStream(false);
                using (var document = HtmlConverter.ConvertToDocument(p, pdf, properties)) { }
            }
            workStream.Position = 0;
            return(File(workStream, "application/pdf"));
        }
Пример #4
0
        public string GeneratePdf(PurchaseOrder entity, CancellationToken cancellationToken = default)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // read template
            string templateFile = _uriComposer.ComposeTemplatePath("purchase_order.html");
            string htmlContent  = File.ReadAllText(templateFile);

            htmlContent = MapTemplateValue(htmlContent, entity);

            // prepare destination pdf
            string pdfFileName     = DateTime.Now.ToString("yyyyMMdd_hhmmss_") + Guid.NewGuid().ToString() + ".pdf";
            string fullPdfFileName = _uriComposer.ComposeDownloadPath(pdfFileName);
            ConverterProperties converterProperties = new ConverterProperties();

            HtmlConverter.ConvertToPdf(htmlContent, new FileStream(fullPdfFileName, FileMode.Create), converterProperties);

            return(fullPdfFileName);
        }
Пример #5
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.Exception"/>
        private void RunConvertToElements(String testName, bool tagged)
        {
            FileStream  source      = new FileStream(sourceFolder + testName + ".html", FileMode.Open, FileAccess.Read);
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + testName + ".pdf"));

            if (tagged)
            {
                pdfDocument.SetTagged();
            }
            Document            layoutDocument = new Document(pdfDocument);
            ConverterProperties props          = new ConverterProperties();

            foreach (IElement element in HtmlConverter.ConvertToElements(source, props))
            {
                if (element is IBlockElement)
                {
                    layoutDocument.Add((IBlockElement)element);
                }
            }
            layoutDocument.Close();
            pdfDocument.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + testName + ".pdf", sourceFolder
                                                                             + "cmp_" + testName + ".pdf", destinationFolder, "diff01_"));
        }
Пример #6
0
        public byte[] GetEventTicket(Event eventU, User user)
        {
            //string FileInputPath = Path.Combine(Directory.GetCurrentDirectory(), "..\\Study.EventManager.Services", "Resources", "TikectTemplateIn.html");
            string       FileInputPath = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "TikectTemplateIn.html");
            StreamReader str           = new StreamReader(FileInputPath);
            string       MailText      = str.ReadToEnd();

            str.Close();

            string foroUrl;

            if (eventU.FotoUrl == null)
            {
                foroUrl = "src='https://eventmanagerstoragefiles.blob.core.windows.net/eventfotoscontainer/logoEvent.JPG'";
            }
            else
            {
                foroUrl = "src='" + eventU.FotoUrl + "'";
            }
            var imgBase64 = _generateQRCode.QRCode(_urlAdress);
            var mailText  = MailText.Replace("[EventFoto]", foroUrl)
                            .Replace("[USERNAME]", user.FirstName + " " + user.LastName)
                            .Replace("[NAME]", eventU.Name)
                            .Replace("[HOLDING]", eventU.HoldingDate.ToString())
                            .Replace("[DESCRIPTION]", eventU.Description)
                            .Replace("[QRCode]", imgBase64);


            MemoryStream        memStream           = new MemoryStream();
            ConverterProperties converterProperties = new ConverterProperties();

            HtmlConverter.ConvertToPdf(mailText, memStream);
            byte[] pdfByte = memStream.ToArray();

            return(pdfByte);
        }
Пример #7
0
        public void ManipulatePdf(String htmlSource, String pdfDest, String freeFontsDirectory)
        {
            // In pdfHTML the iText layouting mechanism now works in HTML rendering mode. In order
            // to switch to the iText default rendering mode, you should declare a custom ICssApplierFactory
            // in which to create a custom ICssApplier for the body node. Then set the default rendering mode
            // property for the property container.
            ICssApplierFactory customCssApplierFactory = new DefaultModeCssApplierFactory();

            // Starting from pdfHTML version 3.0.0 the GNU Free Fonts family (e.g. FreeSans) that were shipped together with the pdfHTML distribution
            // are now replaced by Noto fonts. If your HTML file contains characters which are not supported by standard PDF fonts (basically most of the
            // characters except latin script and some of the symbol characters, e.g. cyrillic characters like in this sample) and also if no other fonts
            // are specified explicitly by means of iText `FontProvider` class or CSS `@font-face` rule, then pdfHTML shipped fonts covering a wide range
            // of glyphs are used instead. In order to replicate old behavior, one needs to exclude from `FontProvider` the fonts shipped by default and
            // provide GNU Free Fonts instead. GNU Free Fonts can be found at https://www.gnu.org/software/freefont/.
            FontProvider fontProvider = new DefaultFontProvider(true, false, false);

            fontProvider.AddDirectory(freeFontsDirectory);

            ConverterProperties converterProperties = new ConverterProperties()
                                                      .SetBaseUri(freeFontsDirectory)
                                                      // Try removing registering of custom DefaultModeCssApplierFactory to compare legacy behavior
                                                      // with the newly introduced. You would notice that now lines spacing algorithm is changed:
                                                      // line spacing is considerably smaller and is closer compared to browsers rendering.
                                                      // You would also notice that now single image in a line behaves according to HTML's "noQuirks" mode:
                                                      // there's an additional "spacing" underneath the image which depends on element's `line-height` and
                                                      // `font-size` CSS properties.
                                                      .SetCssApplierFactory(customCssApplierFactory)
                                                      .SetFontProvider(fontProvider);

            // When converting using the method #convertToElements to change the rendering mode you must also
            // use the flag Property.RENDERING_MODE. However it must be added to the elements from the
            // resulting list before adding these elements to the document. Then the elements will be
            // placed in the specified mode.
            HtmlConverter.ConvertToPdf(new FileStream(htmlSource, FileMode.Open, FileAccess.Read),
                                       new FileStream(pdfDest, FileMode.Create), converterProperties);
        }
Пример #8
0
        public virtual void TestThatCssIsReleasedAfterConversion()
        {
            String dirName        = "CssIsReleased/";
            String htmlFileName   = "cssIsReleased.html";
            String cssFileName    = "cssIsReleased.css";
            String sourceHtmlFile = sourceFolder + dirName + htmlFileName;
            String sourceCssFile  = sourceFolder + dirName + cssFileName;
            String workDir        = destinationFolder + dirName;

            CreateDestinationFolder(workDir);
            String targetPdfFile   = workDir + "target.pdf";
            String workDirHtmlFile = workDir + htmlFileName;
            String workDirCssFile  = workDir + cssFileName;

            File.Copy(System.IO.Path.Combine(sourceHtmlFile), System.IO.Path.Combine(workDirHtmlFile));
            File.Copy(System.IO.Path.Combine(sourceCssFile), System.IO.Path.Combine(workDirCssFile));
            ConverterProperties properties = new ConverterProperties().SetBaseUri(workDir);

            HtmlConverter.ConvertToPdf(new FileInfo(workDirHtmlFile), new FileInfo(targetPdfFile), properties);
            FileInfo resourceToBeRemoved = new FileInfo(workDirCssFile);

            FileUtil.DeleteFile(resourceToBeRemoved);
            NUnit.Framework.Assert.IsFalse(resourceToBeRemoved.Exists);
        }
        public void CreateHTML(Dictionary <SignUp, List <ReportSlot> > SignUpData, string FolderPath, bool SeparateFile, DateTime RequestedDate, string FileName)
        {
            string        FilePath = FileName;
            List <string> AllPages = new List <string>();

            foreach (var roster in SignUpData)
            {
                Dispatcher.Invoke((Action)(() => StatusUpdates.Content = string.Format("Creating PDF for {0}", roster.Key.Title)));
                // Bin slots into times
                Dictionary <DateTime, List <ReportSlot> > binnedSlots = new Dictionary <DateTime, List <ReportSlot> >();
                foreach (var slot in roster.Value)
                {
                    if (binnedSlots.ContainsKey(slot.StartTime))
                    {
                        binnedSlots[slot.StartTime].Add(slot);
                    }
                    else
                    {
                        List <ReportSlot> newList = new List <ReportSlot>();
                        newList.Add(slot);
                        binnedSlots.Add(slot.StartTime, newList);
                    }
                }
                // Sort binned slots by time
                binnedSlots = binnedSlots.OrderBy(training => training.Key).ToDictionary(training => training.Key, training => training.Value);

                StringWriter stringWriter = new StringWriter();
                using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
                {
                    writer.WriteLine("<!DOCTYPE html>");
                    writer.WriteLine("<html lang=\"en\">");
                    writer.RenderBeginTag(HtmlTextWriterTag.Head);
                    writer.WriteLine();
                    writer.WriteLine("<meta charset=\"utf-8\" />");
                    writer.RenderBeginTag(HtmlTextWriterTag.Title);
                    writer.Write("Roster for WSTPC Training Sign Ups");
                    writer.RenderEndTag();
                    writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                    writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                    writer.AddAttribute(HtmlTextWriterAttribute.Href, "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css");
                    writer.RenderBeginTag(HtmlTextWriterTag.Link);
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Style);
                    writer.WriteLine("tr,h5,h3{font-family:Helvetica;}");
                    writer.RenderEndTag();
                    writer.RenderEndTag();

                    writer.RenderBeginTag(HtmlTextWriterTag.Body);
                    writer.RenderBeginTag(HtmlTextWriterTag.H3);
                    writer.Write(roster.Key.Title + " Training Roster - " + roster.Value[0].StartTime.ToString("M/dd/yyyy"));
                    writer.RenderEndTag();
                    // Begin Tables
                    foreach (var trainingGroup in binnedSlots)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "noPageBreak");
                        writer.AddStyleAttribute("page-break-inside", "avoid");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.RenderBeginTag(HtmlTextWriterTag.H5);
                        writer.Write(trainingGroup.Key.ToString("h:mm tt") + " - " + trainingGroup.Value[0].SlotName);
                        writer.RenderEndTag();
                        // Begin actual tables
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "table table-bordered");
                        writer.AddStyleAttribute("font-size", "11pt");
                        writer.RenderBeginTag(HtmlTextWriterTag.Table);
                        writer.RenderBeginTag(HtmlTextWriterTag.Thead);
                        writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                        // Header Rows
                        writer.WriteLine("<th scope=\"col\">First Name</th>");
                        writer.WriteLine("<th scope=\"col\">Last Name</th>");
                        writer.WriteLine("<th scope=\"col\">Email</th>");

                        if (trainingGroup.Value[0].CustomQuestions != null)
                        {
                            for (int i = 0; i < trainingGroup.Value[0].CustomQuestions.Count; i++)
                            {
                                writer.WriteLine("<th scope=\"col\"></th>");
                            }
                        }
                        writer.WriteLine("<th scope=\"col\">Initial</th>");

                        writer.RenderEndTag();
                        writer.RenderEndTag();

                        // List Signup slots
                        writer.RenderBeginTag(HtmlTextWriterTag.Tbody);
                        foreach (var slot in trainingGroup.Value)
                        {
                            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                            writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            writer.Write(slot.FirstName);
                            writer.RenderEndTag();
                            writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            writer.Write(slot.LastName);
                            writer.RenderEndTag();
                            writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            writer.Write(slot.Email);
                            writer.RenderEndTag();
                            // Custom Questions
                            if (slot.CustomQuestions != null)
                            {
                                for (int i = 0; i < slot.CustomQuestions.Count; i++)
                                {
                                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                                    writer.Write(slot.CustomQuestions[i].Value);
                                    writer.RenderEndTag();
                                }
                            }
                            writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            writer.RenderEndTag();
                            writer.RenderEndTag();
                        }
                        writer.RenderEndTag(); // </tbody>
                        writer.RenderEndTag(); // </table>
                        writer.RenderEndTag();
                    }
                    writer.RenderEndTag();
                    writer.WriteLine("</html>");
                }

                string      tempFilePath = FolderPath + "\\" + roster.Key.Title + " " + RequestedDate.ToString("M-dd-yyyy") + ".pdf";
                PdfDocument PDF          = new PdfDocument(new PdfWriter(tempFilePath));

                ConverterProperties converterProperties = new ConverterProperties();
                HtmlConverter.ConvertToPdf(stringWriter.ToString(), PDF, converterProperties);

                AllPages.Add(tempFilePath);
            }
            Dispatcher.Invoke((Action)(() => StatusUpdates.Content = "Combining rosters and opening PDF"));
            try
            {
                PdfDocument MergedPDF = new PdfDocument(new PdfWriter(FilePath));
                PdfMerger   merger    = new PdfMerger(MergedPDF);
                foreach (var PDFFilePath in AllPages)
                {
                    PdfDocument PDF = new PdfDocument(new PdfReader(PDFFilePath));
                    merger.Merge(PDF, 1, PDF.GetNumberOfPages());
                    PDF.Close();
                    if (!SeparateFile)
                    {
                        File.Delete(PDFFilePath);
                    }
                    else
                    {
                        System.Diagnostics.Process.Start(PDFFilePath);
                    }
                }
                MergedPDF.Close();
                System.Diagnostics.Process.Start(FilePath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error Saving File", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #10
0
        public async Task <IActionResult> Convert()
        {
            StringValues clientParam;
            StringValues keyParam;
            StringValues orientationParam;
            StringValues pageSizeParam;
            var          hasClient      = Request.Query.TryGetValue("client", out clientParam);
            var          hasKey         = Request.Query.TryGetValue("key", out keyParam);
            var          hasOrientation = Request.Query.TryGetValue("orientation", out orientationParam);
            var          hasPageSize    = Request.Query.TryGetValue("pageSize", out pageSizeParam);
            var          client         = hasClient && clientParam.Count > 0 ? clientParam[0] : "";
            var          key            = hasKey && keyParam.Count > 0 ? keyParam[0] : "";
            var          orientation    = hasOrientation && orientationParam.Count > 0 ? orientationParam[0] : "portrait";
            var          pageSize       = hasPageSize && pageSizeParam.Count > 0 ? pageSizeParam[0] : "A4";

            if (!_clientKeys.ContainsKey(client) || _clientKeys[client] != key)
            {
                return(new NotFoundResult());
            }

            var formData = HttpContext.Request.Form;
            var files    = formData.Files;
            var docFile  = files.Where(f => f.FileName == "doc.html").FirstOrDefault();

            IActionResult response = null;

            if (docFile != null)
            {
                var tempFolder = $"{System.IO.Path.GetTempPath()}{Guid.NewGuid()}";
                Directory.CreateDirectory(tempFolder);

                foreach (var file in files)
                {
                    if (file.FileName != "doc.html")
                    {
                        await System.IO.File.WriteAllBytesAsync($"{tempFolder}/{file.FileName}", ReadAllBytes(file.OpenReadStream()));
                    }
                }

                try
                {
                    using (var htmlSource = docFile.OpenReadStream())
                        using (var pdfDest = new ByteArrayOutputStream())
                        {
                            var writer = new PdfWriter(pdfDest);
                            var pdfDoc = new PdfDocument(writer);
                            pdfDoc.SetTagged();

                            PageSize ps = PageSize.A4;

                            if (pageSize == "A3")
                            {
                                ps = PageSize.A3;
                            }

                            if (orientation == "landscape")
                            {
                                ps = ps.Rotate();
                            }

                            pdfDoc.SetDefaultPageSize(ps);

                            var converterProperties = new ConverterProperties();

                            var fp = new DefaultFontProvider();
                            fp.AddDirectory(tempFolder);
                            converterProperties.SetFontProvider(fp);

                            converterProperties.SetImmediateFlush(true);
                            converterProperties.SetBaseUri(new Uri(tempFolder).AbsoluteUri);
                            HtmlConverter.ConvertToPdf(htmlSource, pdfDoc, converterProperties);
                            var bytes = pdfDest.ToArray();
                            response = new FileContentResult(bytes, "application/pdf");
                        }
                }
                catch (Exception ex)
                {
                    response = StatusCode(500, new { error = ex.Message, stackTrace = ex.StackTrace });
                }

                Directory.Delete(tempFolder, true);
            }
            else
            {
                response = StatusCode((int)HttpStatusCode.BadRequest, new { error = "No doc file provided" });
            }

            return(response);
        }
Пример #11
0
        /// <summary>
        /// Attaches the HTML content stored in a document node to
        /// an existing PDF document, using specific converter properties,
        /// and returning an iText
        /// <see cref="iText.Layout.Document"/>
        /// object.
        /// </summary>
        /// <param name="documentNode">the document node with the HTML</param>
        /// <param name="pdfDocument">
        /// the
        /// <see cref="iText.Kernel.Pdf.PdfDocument"/>
        /// instance
        /// </param>
        /// <param name="converterProperties">
        /// the
        /// <see cref="iText.Html2pdf.ConverterProperties"/>
        /// instance
        /// </param>
        /// <returns>
        /// an iText
        /// <see cref="iText.Layout.Document"/>
        /// object
        /// </returns>
        public static Document Attach(IDocumentNode documentNode, PdfDocument pdfDocument, ConverterProperties converterProperties
                                      )
        {
            IHtmlProcessor processor = new DefaultHtmlProcessor(converterProperties);

            return(processor.ProcessDocument(documentNode, pdfDocument));
        }
Пример #12
0
        /// <summary>
        /// Attaches the HTML content stored in a document node to
        /// a list of
        /// <see cref="iText.Layout.Element.IElement"/>
        /// objects.
        /// </summary>
        /// <param name="documentNode">the document node with the HTML</param>
        /// <param name="converterProperties">
        /// the
        /// <see cref="iText.Html2pdf.ConverterProperties"/>
        /// instance
        /// </param>
        /// <returns>
        /// the list of
        /// <see cref="iText.Layout.Element.IElement"/>
        /// objects
        /// </returns>
        public static IList <IElement> Attach(IDocumentNode documentNode, ConverterProperties converterProperties)
        {
            IHtmlProcessor processor = new DefaultHtmlProcessor(converterProperties);

            return(processor.ProcessElements(documentNode));
        }
Пример #13
0
        public static byte[] ConvertToPdfWithTags(string html, string title, string docOptions)
        {
            DocOptions documentOptions = DocOptions.None;

            if (!string.IsNullOrEmpty(docOptions))
            {
                int options;
                if (int.TryParse(docOptions, out options))
                {
                    documentOptions = (DocOptions)options;
                }
            }
            PdfFontFactory.RegisterDirectory(System.Web.Hosting.HostingEnvironment.MapPath("~/content/fonts/"));
            ConverterProperties props = new ConverterProperties();

            FontProvider fp = new FontProvider();

            fp.AddDirectory(System.Web.Hosting.HostingEnvironment.MapPath("~/content/fonts/"));
            props.SetFontProvider(fp);
            props.SetTagWorkerFactory(new DefaultTagWorkerFactory());

            ImageData imageFirst =
                ImageDataFactory.Create(System.Web.Hosting.HostingEnvironment.MapPath(headerPage1));

            ImageData imageAll =
                ImageDataFactory.Create(System.Web.Hosting.HostingEnvironment.MapPath(headerAllPages));

            using (var workStream = new MemoryStream())
            {
                using (var pdfWriter = new PdfWriter(workStream, new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                         (PdfVersion.PDF_2_0).SetFullCompressionMode(true)))
                {
                    PdfDocument pdfDoc = new PdfDocument(pdfWriter);
                    pdfDoc.GetCatalog().SetLang(new PdfString("en-GB"));


                    pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
                    if (documentOptions > 0)
                    {
                        pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new PublicReportHeaderFooter(documentOptions, title, imageFirst, imageAll));
                    }
                    //Set meta tags
                    var pdfMetaData = pdfDoc.GetDocumentInfo();
                    pdfMetaData.AddCreationDate();
                    pdfMetaData.GetProducer();
                    pdfMetaData.SetCreator("iText Software");
                    //Set the document to be tagged
                    pdfDoc.SetTagged();

                    //Extra metadata tags available
                    //pdfMetaData.SetAuthor("");
                    using (var document = HtmlConverter.ConvertToDocument(html, pdfDoc, props))
                    {
                        //Can do more with document here if necessary
                    }

                    //Returns the written-to MemoryStream containing the PDF.
                    return(workStream.ToArray());
                }
            }
        }
Пример #14
0
 /// <summary>Instantiates a new default html processor.</summary>
 /// <param name="converterProperties">the converter properties</param>
 public DefaultHtmlProcessor(ConverterProperties converterProperties)
 {
     this.context = new ProcessorContext(converterProperties);
 }
Пример #15
0
        public static byte[] ConvertToPdf(byte[] html)
        {
            byte[] pdf = null;

            using (var ms = new MemoryStream())
            {
                ConverterProperties properties = new ConverterProperties();
                // properties.SetBaseUri("");
                properties.SetOutlineHandler(OutlineHandler.CreateStandardHandler());

                PdfDocument pdfDocument = new PdfDocument(new PdfWriter(ms));
                PageSize    pageSize    = PageSize.Default;

                string metaPageSize = HtmlHelper.ObtenerMetaContent(html, RiskConstants.META_PAGE_SIZE);
                switch (metaPageSize.ToUpper())
                {
                case "A3":
                    pageSize = PageSize.A3;
                    break;

                case "A4":
                    pageSize = PageSize.A4;
                    break;

                case "A5":
                    pageSize = PageSize.A5;
                    break;

                case "A6":
                    pageSize = PageSize.A6;
                    break;

                case "LEGAL":
                    pageSize = PageSize.LEGAL;
                    break;

                case "LETTER":
                    pageSize = PageSize.LETTER;
                    break;

                case "EXECUTIVE":
                    pageSize = PageSize.EXECUTIVE;
                    break;

                default:
                    pageSize = PageSize.Default;
                    break;
                }

                string metaPageOrientation = HtmlHelper.ObtenerMetaContent(html, RiskConstants.META_PAGE_ORIENTATION);
                if (metaPageOrientation.Equals(RiskConstants.ORIENTACION_HORIZONTAL, StringComparison.OrdinalIgnoreCase))
                {
                    pageSize = pageSize.Rotate();
                }

                pdfDocument.SetDefaultPageSize(pageSize);
                Document document = HtmlConverter.ConvertToDocument(new MemoryStream(html), pdfDocument, properties);
                document.Close();

                pdf = ms.ToArray();
            }

            return(pdf);
        }
Пример #16
0
 /// <summary>Instantiates a new default html processor.</summary>
 /// <param name="converterProperties">the converter properties</param>
 public DefaultHtmlProcessor(ConverterProperties converterProperties) {
     // TODO <tbody> is not supported. Styles will be propagated anyway
     // Content from <tr> is thrown upwards to parent, in other cases CSS is inherited anyway
     // TODO implement
     this.context = new ProcessorContext(converterProperties);
 }
        private ParseBodiesListResult ParseBodiesList(ref Document document, List <BA_Body> bodyItemList, int mainFontSize, bool addToTOC)
        {
            ParseBodiesListResult result = new ParseBodiesListResult()
            {
                TOCItems = new List <Tuple <string, int> >()
            };

            //we loop trough the bodies of the item article
            foreach (var body in bodyItemList)
            {
                if (body.BodyContentType == BodyContentType.Image)
                {
                    iText.Layout.Element.Image image = new Image(ImageDataFactory.Create(body.content));
                    var imageWidth  = image.GetImageWidth();
                    var imageHeight = image.GetImageHeight();

                    var documentWidth  = defaultPageSize.GetWidth();
                    var documentHeight = defaultPageSize.GetHeight();
                    var leftMargin     = document.GetLeftMargin();
                    var righttMargin   = document.GetRightMargin();
                    var topMargin      = document.GetTopMargin();
                    var bottomMargin   = document.GetBottomMargin();

                    if (imageHeight > (documentHeight - ((topMargin + bottomMargin) * 1.3)))
                    {
                        float newHeight = (float)(documentHeight - ((topMargin + bottomMargin) * 1.3) - 5f);
                        float newWidth  = (newHeight / imageHeight) * imageWidth;
                        image.ScaleToFit(newWidth, newHeight);
                        imageWidth  = newWidth;
                        imageHeight = newHeight;
                    }
                    //if the image is to large for the page
                    if (imageWidth > (documentWidth - ((leftMargin + righttMargin) * 1.3)))
                    {
                        float newWidth  = (float)((documentWidth - ((leftMargin + righttMargin) * 1.3)) - 5f);
                        float newHeight = (newWidth / imageWidth) * imageHeight;
                        image.ScaleToFit(newWidth, newHeight);
                    }

                    Paragraph paragraph = new Paragraph("").Add(image);
                    //paragraph.SetPaddingBottom(10);
                    document.Add(paragraph);
                }
                else
                {
                    var    paragraphs  = new List <Paragraph>();
                    string bodyContent = null;
                    if (decodeHTML)
                    {
                        //the body can contain html code, we parse it with itext pdf
                        var properties = new ConverterProperties();
                        IList <IElement> elementList           = HtmlConverter.ConvertToElements(body.content, properties);
                        bool             convertedSuccessfully = false;
                        //somehow it can reurn multiple items
                        foreach (var element in elementList)
                        {
                            if (element is Paragraph)
                            {
                                paragraphs.Add(element as Paragraph);
                            }
                        }
                        //if there is no paragraph to convert, add the normal text paragraph
                        if (paragraphs.Any() == false)
                        {
                            paragraphs.Add(new Paragraph(body.content));
                        }
                    }
                    else
                    {
                        bodyContent = GeneralUtils.HtmlDecode(GeneralUtils.StripHTML(body.content));
                        paragraphs.Add(new Paragraph(bodyContent));
                    }

                    //loop through the paragraphs
                    foreach (var paragraph in paragraphs)
                    {
                        //Build action: EMbeded Resource - ProjectName.Folder.Folder.filename
                        //default paragraph font
                        var     bytes         = GeneralUtils.GetFontBytes(Constants.FONT_SWIFT400);
                        PdfFont font          = PdfFontFactory.CreateFont(bytes, "UTF-8", true);
                        float   fontSizeRatio = 1.0f;
                        if (body.BodyContentType == BodyContentType.Hl1)
                        {
                            bytes         = GeneralUtils.GetFontBytes(Constants.FONT_CENTURY300);
                            font          = PdfFontFactory.CreateFont(bytes, "ISO-8859-1", true);
                            fontSizeRatio = h1FontSizeRatio;
                            paragraph.SetFixedLeading((mainFontSize * fontSizeRatio) / 1.1f);
                            //add TOC for later on creation
                            //the H!s of the subitems do not need to be created as TOC

                            if (addToTOC)
                            {
                                int currentPage = document.GetPdfDocument().GetNumberOfPages();
                                result.TOCItems.Add(new Tuple <string, int>(bodyContent, currentPage));
                            }
                        }
                        else if (body.BodyContentType == BodyContentType.Hl2)
                        {
                            bytes         = GeneralUtils.GetFontBytes(Constants.FONT_SWIFT700);
                            font          = PdfFontFactory.CreateFont(bytes, "ISO-8859-1", true);
                            fontSizeRatio = h2FontSizeRatio;
                        }
                        else if (body.BodyContentType == BodyContentType.Kicker)
                        {
                            bytes         = GeneralUtils.GetFontBytes(Constants.FONT_PROXIMA_NOVA500);
                            font          = PdfFontFactory.CreateFont(bytes, "ISO-8859-1", true);
                            fontSizeRatio = kickerFontSizeRatio;
                        }
                        else if (body.BodyContentType == BodyContentType.Byline)
                        {
                            bytes         = GeneralUtils.GetFontBytes(Constants.FONT_PROXIMA_NOVA200);
                            font          = PdfFontFactory.CreateFont(bytes, "ISO-8859-1", true);
                            fontSizeRatio = bylineFontSizeRatio;
                        }
                        else if (body.BodyContentType == BodyContentType.Intro)
                        {
                            bytes         = GeneralUtils.GetFontBytes(Constants.FONT_ABADI200);
                            font          = PdfFontFactory.CreateFont(bytes, "ISO-8859-1", true);
                            fontSizeRatio = introFontSizeRatio;
                        }
                        else if (body.BodyContentType == BodyContentType.Streamer)
                        {
                            bytes         = GeneralUtils.GetFontBytes(Constants.FONT_SWIFT700);
                            font          = PdfFontFactory.CreateFont(bytes, "ISO-8859-1", true);
                            fontSizeRatio = streamerFontSizeRatio;
                            paragraph.SetPaddingTop(25);
                            paragraph.SetPaddingBottom(25);
                        }

                        int fontSize = (int)Math.Ceiling(mainFontSize * fontSizeRatio);
                        paragraph.SetFont(font);
                        paragraph.SetFontSize(fontSize);
                        //paragraph.SetPaddingBottom(10);
                        document.Add(paragraph);
                    }
                }
            }
            document.Add(new Paragraph(Environment.NewLine));

            return(result);
        }
        public void ExportEmails(string query, string exportPath)
        {
            var emailThreads = _googleApiService.GetEmailThreads(query);

            foreach (var emailThread in emailThreads)
            {
                try
                {
                    var emailThreadDate    = emailThread.Emails.Last().DateCreated.ToString("yyyy-MM-dd HH-mm-ss");
                    var emailThreadSubject = emailThread.Emails.First().Subject.ToValidFileName();
                    var emailThreadSender  = new MailAddress(emailThread.Emails.First().From);
                    var pdfFilename        = Path.Combine(exportPath, $"{emailThreadDate} - {emailThreadSender.Address} - {emailThreadSubject}.pdf");

                    _logger.LogInformation($"Create new pdf, Filename={pdfFilename}");

                    using (var pdfDocument = new PdfDocument(new PdfWriter(pdfFilename)))
                    {
                        var pdfMerger = new PdfMerger(pdfDocument);

                        foreach (var email in emailThread.Emails)
                        {
                            string emailContent;
                            if (email.Content.Any(x => x.MimeType == "text/html"))
                            {
                                emailContent = email.Content.First(x => x.MimeType == "text/html").Content;
                            }
                            else
                            {
                                emailContent = $"<html><head></head><body><pre>{email.Content.First().Content}</pre></body></html>";
                            }

                            if (Regex.IsMatch(emailContent, "(<head.*?>)"))
                            {
                                var styleToInject = $@"
<style>
table.sl-header td {{
    font-family: Helvetica;
    font-size: 14px;
}}
</style>";

                                emailContent = Regex.Replace(emailContent, $"(<head.*?>)", $"$1{styleToInject}");
                            }

                            if (Regex.IsMatch(emailContent, "(<body.*?>)"))
                            {
                                var descriptionToInject = $@"
<table class=""sl-header"">
<tr>
    <td width=""100"">Created at</td>
    <td>{email.DateCreated}</td>
</tr>
<tr>
    <td>From</td>
    <td>{HttpUtility.HtmlEncode(email.From)}</td>
</tr>
<tr>
    <td>To</td>
    <td>{HttpUtility.HtmlEncode(email.To)}</td>
</tr>
<tr>
    <td>Subject</td>
    <td>{email.Subject}
</tr>
</table>
<br/><hr/><br/>";

                                emailContent = Regex.Replace(emailContent, $"(<body.*?>)", $"$1{descriptionToInject}");

                                if (false)
                                {
                                    emailContent = Regex.Replace(emailContent, @"<style>\s+@media.*?<\/style>", "", RegexOptions.Singleline);
                                }
                            }

                            byte[] byteArray = Encoding.UTF8.GetBytes(emailContent);

                            using (var htmlSource = new MemoryStream(byteArray))
                            {
                                using (var pdfWriteStream = new MemoryStream())
                                {
                                    var converterProperties = new ConverterProperties();
                                    HtmlConverter.ConvertToPdf(htmlSource, pdfWriteStream, converterProperties);

                                    _logger.LogInformation($"Add new pdf page");
                                    var emailPdf = new PdfDocument(new PdfReader(new MemoryStream(pdfWriteStream.ToArray())));
                                    pdfMerger.Merge(emailPdf, 1, emailPdf.GetNumberOfPages());

                                    foreach (var attachment in email.Attachments.Where(x => x.MimeType == "application/pdf"))
                                    {
                                        _logger.LogInformation($"Add new pdf page");
                                        var attachmentPdf = new PdfDocument(new PdfReader(new MemoryStream(attachment.Data)));
                                        pdfMerger.Merge(attachmentPdf, 1, attachmentPdf.GetNumberOfPages());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "PDF conversion error");
                }
            }
        }
Пример #19
0
        public Tuple <string, bool> CreateCard(List <Batch> batchList)
        {
            var result     = "";
            var boolResult = true;

            try
            {
                var htmlCard = new List <string>();
                var appPath  = ConfigurationManager.AppSettings["route"];

                var cardFormat   = Path.Combine(appPath, "CardFormat\\CardLayout.htm");
                var readHeader   = new StreamReader(cardFormat);
                var headerFormat = readHeader.ReadToEnd();
                readHeader.Close();

                var tableFormat = Path.Combine(appPath, "CardFormat\\TableLayout.htm");
                var exitRoute   = Path.Combine(appPath, "TempFiles\\Cards.pdf");

                if (!routeManager.CheckIfOpen(exitRoute))
                {
                    var htmlTableFormat = File.Open(tableFormat, FileMode.Open, FileAccess.Read);
                    var formatReader    = new StreamReader(htmlTableFormat);
                    var shape           = formatReader.ReadToEnd();
                    formatReader.Close();
                    var userFormat = string.Empty;

                    htmlCard.Add(headerFormat);
                    htmlCard.Add("<body>");

                    foreach (var item in batchList)
                    {
                        userFormat = shape;
                        userFormat = userFormat.Replace("{Name}", item.PersonName);
                        userFormat = userFormat.Replace("{Dep}", item.Department);
                        userFormat = userFormat.Replace("{Pos}", item.Position);
                        userFormat = userFormat.Replace("{No}", item.EmployeeNo);
                        userFormat = userFormat.Replace("{Sangre}", item.Bloodtype);
                        userFormat = userFormat.Replace("{IMSS}", item.IMSSNo);
                        userFormat = userFormat.Replace("{Contacto}", item.EmerContactName);
                        userFormat = userFormat.Replace("{TelC}", item.EmerContactPhone);
                        userFormat = userFormat.Replace("{Par}", item.EmerContactRelationship);
                        userFormat = userFormat.Replace("{EmpImg}", Regex.Replace(item.UserImageRoute, @"\s+", "%20"));
                        htmlCard.Add(userFormat);
                    }

                    htmlCard.Add("</body>");
                    htmlCard.Add("</html>");

                    var completedFile = Path.Combine(appPath, "CardFormat\\FinalFormat.htm");
                    if (!File.Exists(completedFile))
                    {
                        File.Create(completedFile).Dispose();
                    }

                    using (var streamWriter = new StreamWriter(completedFile))
                    {
                        streamWriter.WriteLine(string.Join(Environment.NewLine, htmlCard));
                        streamWriter.Flush();
                    }

                    var streamReader = new StreamReader(completedFile);
                    var finalFormat  = streamReader.ReadToEnd();
                    streamReader.Close();

                    var fileStream          = File.Open(exitRoute, FileMode.OpenOrCreate);
                    var converterProperties = new ConverterProperties();
                    var cssRoute            = Path.Combine(appPath, "CardFormat\\");
                    converterProperties.SetBaseUri(cssRoute);
                    var pdfWriter   = new PdfWriter(fileStream);
                    var pdfDocument = new PdfDocument(pdfWriter);
                    pdfDocument.SetDefaultPageSize(iText.Kernel.Geom.PageSize.A4);
                    var document = HtmlConverter.ConvertToDocument(finalFormat, pdfDocument, converterProperties);
                    document.Close();

                    System.Diagnostics.Process.Start(exitRoute);
                    result = "Document created successfully";
                    return(Tuple.Create(result, boolResult));
                }
                else
                {
                    result     = "Cannot create a new document while it is still open";
                    boolResult = false;
                    return(Tuple.Create(result, boolResult));
                }
            }
            catch (Exception)
            {
                boolResult = false;
                result     = "File failed to be created, please try again";
                return(Tuple.Create(result, boolResult));
            }
        }
Пример #20
0
        public IActionResult Create(string pdfHtmlString, string saveName = null)
        {
            #region Parameters
            // Global Config
            string fontFamily = Configuration["PdfConfig:GlobalConfig:FontFamily"];
            // Path Config
            string descPath = Configuration["PdfConfig:PathConfig:DescPath"];
            string logPath  = Configuration["PdfConfig:PathConfig:LogPath"];
            // MetaData Config
            string title    = Configuration["PdfConfig:MetaData:Title"];
            string author   = Configuration["PdfConfig:MetaData:Author"];
            string creator  = Configuration["PdfConfig:MetaData:Creator"];
            string keywords = Configuration["PdfConfig:MetaData:Keywords"];
            string subject  = Configuration["PdfConfig:MetaData:Subject"];
            // Header Config
            string headerText           = Configuration["PdfConfig:Header:Text"];
            float  headerFontSize       = Convert.ToSingle(Configuration["PdfConfig:Header:FontSize"]);
            string headerFontColor      = Configuration["PdfConfig:Header:FontColor"];
            string headerImageSource    = Configuration["PdfConfig:Header:Image:Source"];
            float  headerImageWidth     = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Width"]);
            float  headerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Left"]);
            float  headerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Top"]);
            // Footer Config
            string footerText           = Configuration["PdfConfig:Footer:Text"];
            double footerFontSize       = Convert.ToDouble(Configuration["PdfConfig:Footer:FontSize"]);
            string footerFontColor      = Configuration["PdfConfig:Footer:FontColor"];
            string footerImageSource    = Configuration["PdfConfig:Footer:Image:Source"];
            float  footerImageWidth     = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Width"]);
            float  footerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Left"]);
            float  footerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Top"]);
            #endregion

            #region Properties & Setting
            // Configure properties for converter | 配置转换器
            ConverterProperties properties = new ConverterProperties();
            // Resources path, store images/fonts for example | 资源路径, 存放如图片/字体等资源
            string resources = Host.WebRootPath + (osInfo.Platform == PlatformID.Unix ? "/src/font/" : "\\src\\font\\");
            // PDF saved path | 生成的PDF文件存放路径
            string desc = string.Empty;
            if (osInfo.Platform == PlatformID.Unix)
            {
                if (!Directory.Exists(descPath))
                {
                    Directory.CreateDirectory(descPath);
                }
                desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf";
            }
            else
            {
                descPath = "D:\\Pdf\\";
                if (!Directory.Exists(descPath))
                {
                    Directory.CreateDirectory(descPath);
                }
                desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf";
            }

            FontProvider fp = new FontProvider();
            // Add Standard fonts libs without chinese support | 添加标准字体库
            // fp.AddStandardPdfFonts();
            fp.AddDirectory(resources);
            properties.SetFontProvider(fp);
            // Set base uri to resource folder | 设置基础uri
            properties.SetBaseUri(resources);

            PdfWriter   writer = new PdfWriter(desc);
            PdfDocument pdfDoc = new PdfDocument(writer);
            // Set PageSize | 设置页面大小
            pdfDoc.SetDefaultPageSize(PageSize.A4);
            // Set Encoding | 设置文本编码方式
            pdfDoc.GetCatalog().SetLang(new PdfString("UTF-8"));

            //Set the document to be tagged | 展示文档标签树
            pdfDoc.SetTagged();
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));

            //https://developers.itextpdf.com/content/itext-7-examples/converting-html-pdf/pdfhtml-header-and-footer-example
            // create pdf font using custom resources | 自定义字体
            PdfFont sourcehansanscn = PdfFontFactory.CreateFont(resources + fontFamily, PdfEncodings.IDENTITY_H);

            Dictionary <string, object> header = new Dictionary <string, object>()
            {
                { "text", headerText },
                { "fontSize", headerFontSize },
                { "fontColor", headerFontColor },
                { "source", Host.WebRootPath + headerImageSource },
                { "width", headerImageWidth },
                { "left", headerImagePositionX },
                { "top", headerImagePositionY }
            };
            Dictionary <string, object> footer = new Dictionary <string, object>()
            {
                { "text", footerText },
                { "fontSize", footerFontSize },
                { "fontColor", footerFontColor },
                { "source", Host.WebRootPath + footerImageSource },
                { "width", footerImageWidth },
                { "left", footerImagePositionX },
                { "top", footerImagePositionY }
            };
            // Header handler | 页头处理
            PdfHeader headerHandler = new PdfHeader(header, sourcehansanscn);
            // Footer handler | 页脚处理
            PdfFooter footerHandler = new PdfFooter(footer, sourcehansanscn);

            // Assign event-handlers
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);

            // Setup custom tagworker factory for better tagging of headers | 设置标签处理器
            DefaultTagWorkerFactory tagWorkerFactory = new DefaultTagWorkerFactory();
            properties.SetTagWorkerFactory(tagWorkerFactory);

            // Setup default outline(bookmark) handler | 设置默认大纲(书签)处理器
            // We used the createStandardHandler() method to create a standard handler.
            // This means that pdfHTML will look for <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.
            // The bookmarks will be created based on the hierarchy of those tags in the HTML file.
            // To enable other tags, read the folllowing article for more details.
            // https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml
            OutlineHandler outlineHandler = OutlineHandler.CreateStandardHandler();
            properties.SetOutlineHandler(outlineHandler);

            // Bookmark | 书签
            // https://developers.itextpdf.com/content/itext-7-examples/itext-7-bookmarks-tocs/toc-first-page
            // https://developers.itextpdf.com/content/best-itext-questions-stackoverview/actions-and-annotations/itext7-how-create-hierarchical-bookmarks
            // https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-6-creating-actions-destinations-and-bookmarks
            // https://developers.itextpdf.com/examples/actions-and-annotations/clone-named-destinations
            // PdfOutline outline = null;
            // outline = CreateOutline(outline, pdfDoc, "bookmark", "bookmark");

            // Meta tags | 文档属性标签
            PdfDocumentInfo pdfMetaData = pdfDoc.GetDocumentInfo();
            pdfMetaData.SetTitle(title);
            pdfMetaData.SetAuthor(author);
            pdfMetaData.AddCreationDate();
            pdfMetaData.GetProducer();
            pdfMetaData.SetCreator(creator);
            pdfMetaData.SetKeywords(keywords);
            pdfMetaData.SetSubject(subject);
            #endregion

            // Start convertion | 开始转化
            //Document document =
            //    HtmlConverter.ConvertToDocument(pdfHtmlString, pdfDoc, properties);

            IList <IElement>   elements        = HtmlConverter.ConvertToElements(pdfHtmlString, properties);
            Document           document        = new Document(pdfDoc);
            CJKSplitCharacters splitCharacters = new CJKSplitCharacters();
            document.SetFontProvider(fp);
            document.SetSplitCharacters(splitCharacters);
            document.SetProperty(Property.SPLIT_CHARACTERS, splitCharacters);
            foreach (IElement e in elements)
            {
                try
                {
                    document.Add((AreaBreak)e);
                }
                catch
                {
                    document.Add((IBlockElement)e);
                }
            }

            // Close and release document | 关闭并释放文档资源
            document.Close();

            return(Content("SUCCESS"));
        }
Пример #21
0
        public ActionResult DocuXmlPDF(int idCab)
        {
            try
            {
                var Org_XML = _db.Documento.FirstOrDefault(z => z.id_cab == idCab).xml_dte.ToString();
                var html    = helper.XmlFo4Pdf(Org_XML.Replace("xmlns=\"http://www.sii.cl/SiiDte\" ", "").Replace("\r\n", ""));

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(Org_XML);
                var          Ted = doc.GetElementsByTagName("TED")[0].OuterXml;
                MemoryStream ms  = new MemoryStream();

                // Convierto el HTML en PDF
                ConverterProperties properties = new ConverterProperties();
                properties.SetBaseUri("http://gs.pso.cl/Master/DocuXml?idCab=4923");
                HtmlConverter.ConvertToPdf(html, ms, properties);

                // Genero el PDF417
                MemoryStream msIMG = new MemoryStream();
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(ms.ToArray());
                PdfStamper stamper = new PdfStamper(reader, msIMG);
                int        n       = reader.NumberOfPages;
                var        msIMG2  = GenerateBarCodeZXing(Ted);
                //Inserto la imagen del PDF417
                iTextSharp.text.Image QR = iTextSharp.text.Image.GetInstance(msIMG2, ImageFormat.Png);
                QR.SetAbsolutePosition(10, 200);
                stamper.GetOverContent(1).AddImage(QR);
                stamper.FormFlattening = false;



                //msIMG.Flush(); // Don't know if this is necessary
                //msIMG.Position = 0;
                //msIMG.Close();

                //iTextSharp.text.pdf.PdfReader reader2 = new iTextSharp.text.pdf.PdfReader(msIMG.ToArray());

                MemoryStream msMargen = new MemoryStream();
                //WriterProperties writerProperties = new WriterProperties();
                Document doc2 = new Document(iTextSharp.text.PageSize.LETTER, 200, 0, 100, 0);
                iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc2, msMargen);



                doc2.Open();
                pdfWriter.Open();
                PdfContentByte cb = pdfWriter.DirectContent;

                var page = pdfWriter.GetImportedPage(reader, 1);

                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);

                //pdfWriter.SetMargins(0, 0, 0, 0);
                //pdfWriter.Close();

                //ms.Close();
                //msIMG.Close();
                doc2.Close();
                stamper.Close();
                reader.Close();

                return(File(msIMG.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf));
            }
            catch (Exception)
            {
                return(null);
            }
        }