public Doc CreatePDFFromString(string htmlData)
        {
            //Create the pdf
            var pdfDoc = new Doc();

            pdfDoc.Rect.Inset(30, 50);
            pdfDoc.Color.String = "255 255 255";

            var pdfID = pdfDoc.AddImageHtml(htmlData, true, 0, true);

            //We now chain subsequent pages together. We stop when we reach a page which wasn't truncated
            while (true)
            {
                pdfDoc.FrameRect();
                if (pdfDoc.GetInfo(pdfID, "Truncated") != "1")
                {
                    break;
                }
                pdfDoc.Page = pdfDoc.AddPage();
                pdfID       = pdfDoc.AddImageToChain(pdfID);
            }

            //After adding the pages we can flatten them. We can't do this until after the pages have been
            //added because flattening will invalidate our previous ID and break the chain.
            for (var i = 1; i <= pdfDoc.PageCount; i++)
            {
                pdfDoc.PageNumber = i;
                pdfDoc.Flatten();
            }
            return(pdfDoc);
        }
Пример #2
0
        public string ConvertHtmlToPdf(string htmlFile)
        {
            var newFileName = string.Format("{0}\\{1}.pdf", Path.GetDirectoryName(htmlFile), Path.GetFileNameWithoutExtension(htmlFile));
            var htmlText    = File.ReadAllText(htmlFile);
            var doc         = new Doc();

            //doc.Rect.Inset(10,10); //create margin
            doc.HtmlOptions.Engine = EngineType.Gecko;
            int id = doc.AddImageHtml(htmlText);

            while (true)
            {
                //doc.FrameRect(); //draw rectangle
                if (!doc.Chainable(id))
                {
                    break;
                }

                doc.Page = doc.AddPage();
                id       = doc.AddImageToChain(id);
            }
            for (int i = 1; i <= doc.PageCount; i++)
            {
                doc.PageNumber = i;
                doc.Flatten();
            }

            doc.Save(newFileName);

            return(newFileName);
        }
Пример #3
0
        public static void HtmlToPdf(string html = null)
        {
            Doc doc = new Doc();

            doc.AddImageHtml(html);
            doc.Save("/Temp/2.pdf");
        }
Пример #4
0
        private byte[] CreateDeliveryAssurancePdf(HttpRequestBase request, string id, int lineNumber, bool resync, ref Doc theDoc)
        {
            int retID = 0;

            theDoc = new Doc();

            if (resync)
            {
                theDoc.HtmlOptions.Engine           = EngineType.Gecko;
                theDoc.HtmlOptions.PageCacheEnabled = false;
                theDoc.HtmlOptions.UseNoCache       = true;
                theDoc.HtmlOptions.PageCacheClear();
                theDoc.HtmlOptions.PageCachePurge();
                theDoc.HtmlOptions.UseResync = true;
            }

            theDoc.Rect.Inset(20, 20);
            theDoc.ClearCachedDecompressedStreams();

            var generatePdfUrl = DeliveryAssuranceHelper.BuildQueryUrl($"{GenerateDeliveryPdfUrl}GeneratePdf",
                                                                       new Dictionary <string, string>()
            {
                { "a", id },
                { "l", lineNumber.ToString() }
            });

            var responseStream = GetWebResponseStream(request, generatePdfUrl);

            if (responseStream != null)
            {
                var outerHtml = FixRelativeLinksToAbsolute(responseStream, request.Url);
                Log.DebugFormat("HtmlResponse with relative links {0}", outerHtml);

                retID = theDoc.AddImageHtml(outerHtml);
            }
            else
            {
                Log.DebugFormat("PDFResponseStream was null");
            }

            //Add Barcode
            theDoc.Rect.String = "360 680 590 725";
            //theDoc.Rect.String = "360 695 590 740";
            var bdf   = BarcodeDrawFactory.Code39WithoutChecksum;
            var image = bdf.Draw(id, 45);

            theDoc.AddImageBitmap(new Bitmap(image), true);

            theDoc.Rect.String = "460 650 530 670";
            theDoc.AddText(id);

            //Add Footer
            theDoc = AddFooter(theDoc, id, lineNumber);

            var theData = theDoc.GetData();

            return(theData);
        }
Пример #5
0
 public ActionResult ExportPdf()
 {
     StreamReader sr = new StreamReader(@"D:\Code\C#\SmallDragon\SmallDragon\Temp\HtmlPage3.html");
     string html = sr.ReadToEnd();
     Doc doc = new Doc();
     doc.AddImageHtml(html);
     doc.Save(@"C:\Users\GuyFawkes\Desktop\New folder\out.pdf");
     doc.Clear();
     System.Diagnostics.Process.Start(@"C:\Users\GuyFawkes\Desktop\New folder\out.pdf");
     return View("Index");
 }
Пример #6
0
        /// <summary>
        /// Appends document with multipage content
        /// </summary>
        private void AppendChainable(Doc doc, String htmlOrUrl, Boolean isUrl = false)
        {
            Int32 blockId = isUrl
                ? doc.AddImageUrl(htmlOrUrl)
                : doc.AddImageHtml(String.Format("<html>{0}</html>", htmlOrUrl));

            while (doc.Chainable(blockId))
            {
                //doc.FrameRect(); // add a black border
                doc.Page = doc.AddPage();
                blockId  = doc.AddImageToChain(blockId);
            }
        }
Пример #7
0
        private static void ExportHtmlToPdf()
        {
            var currentPath  = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var htmlPath     = Path.Combine(currentPath, "template.html");
            var logoPath     = Path.Combine(currentPath, "logo.png");
            var outputPath   = Path.Combine(currentPath, "output\\result.pdf");
            var outputFolder = Path.GetDirectoryName(outputPath);

            var tempFolder   = CreateTempFolder();
            var tempLogoPath = Path.Combine(tempFolder, "logo.png");

            File.Copy(logoPath, tempLogoPath);

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

            var content = File.ReadAllText(htmlPath).Replace("$image_path$", new Uri(tempLogoPath).ToString());

            using (var doc = new Doc())
            {
                doc.Page = doc.AddPage();

                var id = doc.AddImageHtml(content);

                while (true)
                {
                    if (!doc.Chainable(id))
                    {
                        break;
                    }

                    doc.Page = doc.AddPage();
                    id       = doc.AddImageToChain(id);
                }

                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Flatten();
                }

                doc.Save(outputPath);
            }

            Console.WriteLine($"PDF path : {outputPath}");
            Directory.Delete(tempFolder, true);
        }
Пример #8
0
        public static byte[] GetPdfFromHtml(string html)
        {
            Doc thisDoc = new Doc();

            thisDoc.Rect.Height = 770;
            thisDoc.Rect.Bottom = 15;
            int pageId = thisDoc.AddImageHtml(html);

            while (thisDoc.Chainable(pageId))
            {
                thisDoc.Page = thisDoc.AddPage();
                pageId       = thisDoc.AddImageToChain(pageId);
            }
            for (int i = 1; i <= thisDoc.PageCount; i++)
            {
                thisDoc.PageNumber = i;
                thisDoc.Flatten();
            }

            return(thisDoc.GetData());
        }
Пример #9
0
        private void ExportHtmlToPdf(Stream outputStream)
        {
            var htmlPath = Server.MapPath("~/App_Data/template.html");
            var logoPath = Server.MapPath("~/App_Data/logo.png");

            var tempFolder   = CreateTempFolder();
            var tempLogoPath = Path.Combine(tempFolder, "logo.png");

            System.IO.File.Copy(logoPath, tempLogoPath);

            var content = System.IO.File.ReadAllText(htmlPath).Replace("$image_path$", new Uri(tempLogoPath).ToString());

            using (var doc = new Doc())
            {
                doc.Page = doc.AddPage();

                var id = doc.AddImageHtml(content);

                while (true)
                {
                    if (!doc.Chainable(id))
                    {
                        break;
                    }

                    doc.Page = doc.AddPage();
                    id       = doc.AddImageToChain(id);
                }

                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Flatten();
                }

                doc.Save(outputStream);
            }

            Directory.Delete(tempFolder, true);
        }
Пример #10
0
        private byte[] CreateDryingAgreementPdf(HttpRequestBase request, bool resync, ref Doc theDoc)
        {
            var retID = 0;

            theDoc = new Doc();

            if (resync)
            {
                theDoc.HtmlOptions.Engine           = EngineType.Gecko;
                theDoc.HtmlOptions.PageCacheEnabled = false;
                theDoc.HtmlOptions.UseNoCache       = true;
                theDoc.HtmlOptions.PageCacheClear();
                theDoc.HtmlOptions.PageCachePurge();
                theDoc.HtmlOptions.UseResync = true;
            }

            theDoc.Rect.Inset(20, 20);
            theDoc.ClearCachedDecompressedStreams();

            const string generatePdfUrl = "/api/drying-agreement/generatePdf";

            var responseStream = GetWebResponseStream(request, generatePdfUrl);

            if (responseStream != null)
            {
                var outerHtml = FixRelativeLinksToAbsolute(responseStream, request.Url);
                Log.DebugFormat("HtmlResponse with relative links {0}", outerHtml);

                retID = theDoc.AddImageHtml(outerHtml);
            }
            else
            {
                Log.DebugFormat("PDFResponseStream was null");
            }

            var theData = theDoc.GetData();

            return(theData);
        }
        /// <summary>
        /// Returns the PDF for the specified html. The conversion is done using ABCPDF.
        /// </summary>
        /// <param name="html">The html.</param>
        /// <param name="pdf">the PDF</param>
        /// <param name="signatureRect">the location of the signature field</param>
        /// <param name="signaturePage">the page of the signature field</param>
        public static void GetPdfUsingAbc(string html, out byte[] pdf, out XRect signatureRect, out int signaturePage)
        {
            var document = new Doc();

            document.MediaBox.String = "A4";
            document.Color.String    = "255 255 255";
            document.FontSize        = 7;
            /* tag elements marked with "abcpdf-tag-visible: true" */
            document.HtmlOptions.AddTags = true;
            int pageId     = document.AddImageHtml(html, true, 950, true);
            int pageNumber = 1;

            signatureRect = null;
            signaturePage = -1;
            TryIdentifySignatureLocationOnCurrentPage(document, pageId, pageNumber, ref signatureRect, ref signaturePage);
            while (document.Chainable(pageId))
            {
                document.Page = document.AddPage();
                pageId        = document.AddImageToChain(pageId);
                pageNumber++;
                TryIdentifySignatureLocationOnCurrentPage(document, pageId, pageNumber, ref signatureRect, ref signaturePage);
            }
            pdf = document.GetData();
        }
Пример #12
0
        /// <summary>
        /// Create an estimate body in html format, related to an Estimate.
        /// </summary>
        /// <param name="HTML">The HTML.</param>
        /// <param name="estimateid">estimate id.</param>
        /// <param name="theDoc">The doc.</param>
        /// <param name="printCustomerDetails">if set to <c>true</c> [print customer details].</param>
        /// <param name="promotiontypeid">The promotiontypeid.</param>
        /// <returns>Pdf document</returns>
        public Doc PrintEstimateBody(string pdftemplate, int estimateid, Doc theDoc)
        {
            StringBuilder sb       = new StringBuilder();
            StringBuilder tempdesc = new StringBuilder();
            string        tempStr  = string.Empty;

            // Add the Disclaimer/Acknowledgements body text.
            Doc theDoc3 = new Doc();

            theDoc3.MediaBox.SetRect(0, 0, 595, 600);
            theDoc3.Rect.String = "0 0 565 600";

            theDoc3.Color.Color    = System.Drawing.Color.Black;
            theDoc3.Font           = theDoc3.AddFont(Common.PRINTPDF_DEFAULT_FONT);
            theDoc3.TextStyle.Size = Common.PRINTPDF_DISCLAIMER_FONTSIZE;
            theDoc3.TextStyle.Bold = false;
            theDoc3.Rect.Pin       = 0;
            theDoc3.Rect.Position(20, 0);
            theDoc3.Rect.Width           = 400;
            theDoc3.Rect.Height          = 600;
            theDoc3.TextStyle.LeftMargin = 25;

            string disclaimer = Common.getDisclaimer(estimateRevisionId.ToString(), Session["OriginalLogOnState"].ToString(), estimateRevision_internalVersion, estimateRevision_disclaimer_version).Replace("$Token$", tempStr);

            disclaimer = disclaimer.Replace("$printdatetoken$", DateTime.Now.ToString("dd/MMM/yyyy"));
            disclaimer = disclaimer.Replace("$logoimagetoken$", Server.MapPath("~/images/metlog.jpg"));

            if (variationnumber == "--")
            {
                disclaimer = disclaimer.Replace("$DaysExtension$", "&nbsp;");
            }
            else
            {
                disclaimer = disclaimer.Replace("$DaysExtension$", string.Format("EXTENSION OF TIME {0} DAYS (Due to the above variation)", extentiondays));
            }

            // If QLD, then use a real deposit amount in the Agreement
            if (Session["OriginalLogOnStateID"] != null)
            {
                if (Session["OriginalLogOnStateID"].ToString() == "3")
                {
                    DBConnection DBCon = new DBConnection();
                    SqlCommand   Cmd   = DBCon.ExecuteStoredProcedure("spw_checkIfContractDeposited");
                    Cmd.Parameters["@contractNo"].Value = BCContractnumber;
                    DataSet ds     = DBCon.SelectSqlStoredProcedure(Cmd);
                    double  amount = 0;
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        amount = double.Parse(ds.Tables[0].Rows[0]["DepositAmount"].ToString());
                    }
                    if (amount > 0.00)
                    {
                        disclaimer = disclaimer.Replace("$DepositAmount$", "payment of " + String.Format("{0:C}", amount));
                    }
                    else
                    {
                        disclaimer = disclaimer.Replace("$DepositAmount$", "payment as receipted");
                    }
                }
            }

            if (disclaimer.Trim() != "")
            {
                int docid = theDoc3.AddImageHtml(disclaimer);
                while (true)
                {
                    if (!theDoc3.Chainable(docid))
                    {
                        break;
                    }

                    theDoc3.Page = theDoc3.AddPage();
                    docid        = theDoc3.AddImageToChain(docid);
                }
            }

            theDoc.Append(theDoc3);

            return(theDoc);
        }
Пример #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //filter = Request.QueryString["filter"].ToString();
            bool.TryParse(Request.QueryString["fullcomparison"], out fullConparison);
            int.TryParse(Request.QueryString["Source"], out estimateRevisionIdA);
            int.TryParse(Request.QueryString["Destination"], out estimateRevisionIdB);

            GetEstimateHeader(estimateRevisionIdA, out estimateNumber, out revisionTypeA, out revisionNumberA, out effectiveDateA, out homePriceA, out upgradeValueA, out siteworkValueA, out totalPriceA, out ownerA, out statusA, out houseName, out customer, out houseAndLandPackage, out customerDocumentA);
            GetEstimateHeader(estimateRevisionIdB, out estimateNumber, out revisionTypeB, out revisionNumberB, out effectiveDateB, out homePriceB, out upgradeValueB, out siteworkValueB, out totalPriceB, out ownerB, out statusB, out houseName, out customer, out houseAndLandPackage, out customerDocumentB);

            GetEstimateInformation(estimateNumber, out lotAddress, out address);

            revisionTitleA = "Revision " + revisionNumberA.ToString() + " (" + revisionTypeA + ")";
            if (!string.IsNullOrEmpty(customerDocumentA))
            {
                revisionTitleA += " - " + customerDocumentA;
            }

            revisionTitleB = "Revision " + revisionNumberB.ToString() + " (" + revisionTypeB + ")";
            if (!string.IsNullOrEmpty(customerDocumentB))
            {
                revisionTitleB += " - " + customerDocumentB;
            }

            Doc theDoc = new Doc();

            theDoc.MediaBox.SetRect(0, 0, 595, 842);
            theDoc.Rect.String = "30 35 565 812";

            // generate header
            string html = "";

            html = GenerateHeader();

            // generate body
            html = PrintEstimateBody(html);

            // generate PDF

            int theID = theDoc.AddImageHtml(html);

            while (theDoc.Chainable(theID))
            {
                theDoc.Page = theDoc.AddPage();
                theID       = theDoc.AddImageToChain(theID);
            }


            // save PDF in the memory

            Random R = new Random();

            byte[] theData = theDoc.GetData();
            Response.Clear();
            Response.AddHeader("content-type", "application/pdf");
            Response.AddHeader("content-disposition", "inline; filename='EstimateComparison" + "_" + R.Next(1000).ToString() + ".pdf'");

            if (Context.Response.IsClientConnected)
            {
                Context.Response.OutputStream.Write(theData, 0, theData.Length);
                Context.Response.Flush();
            }

            theDoc.Clear();
        }
        public static byte[] GetPdfFromHtml(string html)
        {
            Doc thisDoc = new Doc();

            thisDoc.Rect.Height = 770;
            thisDoc.Rect.Bottom = 15;
            int pageId = thisDoc.AddImageHtml(html);
            while (thisDoc.Chainable(pageId))
            {
                thisDoc.Page = thisDoc.AddPage();
                pageId = thisDoc.AddImageToChain(pageId);
            }
            for (int i = 1; i <= thisDoc.PageCount; i++)
            {
                thisDoc.PageNumber = i;
                thisDoc.Flatten();
            }

            return thisDoc.GetData();
        }
Пример #15
0
        public void CreateFormattedEmailPdf(string from, string sent, string to, string subject, string htmlbody, string pdfFileName)
        {
            /*
             *          Creates a single paged PDF that is formatted in the MS Outlook email print style:
             *
             *               InfoTrack
             *              --------------------------------------------
             *               From:              << from >>
             *               Sent:              << sent >>
             *               To:                << to >>
             *               Subject:           << subject >>
             *
             *
             *               << body >>
             */

            // Constant coordinates (in pixels):
            const double yCoordHeaderLine1               = 780 - 10 - 4;
            const double yCoordHeaderLine2               = 780 - 20 - 5;
            const double yCoordHeaderLine3               = 780 - 30 - 6.2;
            const double yCoordHeaderLine4               = 780 - 40 - 7.1;
            const double xCoordLineLeftMargin            = 35;
            const double xCoordTextLeftMargin            = 37;
            const double xCoordEmailHeaderInfoLeftMargin = 157;
            const double headerLineThickness             = 2.8;
            const double yCoordHeaderLine             = 780;
            const double ySpacingBetweenHeaderAndBody = 35;
            const double bottomMargin      = 50;
            const double yCoordMailboxName = 793;

            // Transform the plain text to HTML
            // var htmlbody = body;

            using (var theDoc = new Doc())
            {
                // Set page size
                theDoc.MediaBox.String = "A4";
                theDoc.Rect.String     = theDoc.MediaBox.String;
                theDoc.Page            = theDoc.AddPage();

                var pageWidth  = theDoc.Rect.Width;
                var pageHeight = theDoc.Rect.Height;

                // Add the mailbox/account name
                var accountNameFont = theDoc.AddFont("Segoe UI-Bold");
                theDoc.FontSize = 12;
                theDoc.Font     = accountNameFont;
                theDoc.Pos.X    = xCoordTextLeftMargin;
                theDoc.Pos.Y    = yCoordMailboxName;
                theDoc.AddText("InfoTrack");

                // Add horizontal header line
                theDoc.Width = headerLineThickness;
                theDoc.AddLine(xCoordLineLeftMargin, yCoordHeaderLine - headerLineThickness / 2,
                               pageWidth - xCoordLineLeftMargin, yCoordHeaderLine - headerLineThickness / 2);

                // Add the email header headings
                theDoc.FontSize = 10;
                theDoc.Pos.X    = xCoordTextLeftMargin;
                theDoc.Pos.Y    = yCoordHeaderLine1;
                theDoc.AddText("From:");

                theDoc.Pos.X = xCoordTextLeftMargin;
                theDoc.Pos.Y = yCoordHeaderLine2;
                theDoc.AddText("Sent:");

                theDoc.Pos.X = xCoordTextLeftMargin;
                theDoc.Pos.Y = yCoordHeaderLine3;
                theDoc.AddText("To:");

                theDoc.Pos.X = xCoordTextLeftMargin;
                theDoc.Pos.Y = yCoordHeaderLine4;
                theDoc.AddText("Subject:");

                // Add the email header values
                var headerInfoFont = theDoc.AddFont("Segoe UI");
                theDoc.Font  = headerInfoFont;
                theDoc.Pos.X = xCoordEmailHeaderInfoLeftMargin;
                theDoc.Pos.Y = yCoordHeaderLine1;
                theDoc.AddText(from);

                theDoc.Pos.X = xCoordEmailHeaderInfoLeftMargin;
                theDoc.Pos.Y = yCoordHeaderLine2;
                theDoc.AddText(sent);

                theDoc.Pos.X = xCoordEmailHeaderInfoLeftMargin;
                theDoc.Pos.Y = yCoordHeaderLine3;
                theDoc.AddText(to);

                theDoc.Rect.Position(xCoordEmailHeaderInfoLeftMargin, yCoordHeaderLine4, XRect.Corner.TopLeft);
                theDoc.Rect.Width = pageWidth - xCoordTextLeftMargin - xCoordEmailHeaderInfoLeftMargin;
                var textObjectId      = theDoc.AddText(subject);
                var endY              = Double.Parse(theDoc.GetInfo(textObjectId, "EndPos").Split(new[] { ' ' })[1]);
                var subjectTextHeight = yCoordHeaderLine4 - endY;

                // Add the email body
                var bodyFont = theDoc.AddFont("Consolas");
                theDoc.Font     = bodyFont;
                theDoc.FontSize = 10;

                theDoc.Rect.Width = pageWidth - (2 * xCoordTextLeftMargin);

                var headerSize = pageHeight - yCoordHeaderLine4 + ySpacingBetweenHeaderAndBody + subjectTextHeight;
                theDoc.Rect.Height = pageHeight - headerSize - bottomMargin;
                theDoc.Rect.Position(xCoordTextLeftMargin, yCoordHeaderLine4 - subjectTextHeight - ySpacingBetweenHeaderAndBody, XRect.Corner.TopLeft);
                theDoc.TextStyle.LineSpacing = 2;

                var chainId   = theDoc.AddImageHtml(htmlbody);
                var topMargin = pageHeight - yCoordMailboxName;

                // Add 1st page number
                theDoc.Rect.Height = 40;
                theDoc.Rect.Position(xCoordTextLeftMargin, 40, XRect.Corner.TopLeft);
                theDoc.HPos = 0.5;
                theDoc.AddText(theDoc.PageNumber.ToString());

                // Add more pages
                var currentPage = 2;
                while (theDoc.Chainable(chainId))
                {
                    theDoc.Rect.Height = pageHeight - topMargin - bottomMargin;
                    theDoc.Rect.Position(xCoordTextLeftMargin, yCoordMailboxName, XRect.Corner.TopLeft);
                    theDoc.Page = theDoc.AddPage();
                    chainId     = theDoc.AddImageToChain(chainId);

                    // Page number
                    theDoc.PageNumber  = currentPage++;
                    theDoc.Rect.Height = 40;
                    theDoc.Rect.Position(xCoordTextLeftMargin, 40, XRect.Corner.TopLeft);
                    theDoc.HPos = 0.5;
                    theDoc.AddText(theDoc.PageNumber.ToString());
                }

                // Save the PDF
                theDoc.Save(pdfFileName);
            }
        }
Пример #16
0
        public byte[] ConvertHtmlString(string customData)
        {
            try
            {
                var theDoc = new Doc();

                theDoc.MediaBox.String = "A4";
                theDoc.SetInfo(0, "License", "141-819-141-276-8435-093");

                theDoc.Rect.Inset(10, 5);
                theDoc.HtmlOptions.AddLinks = true;

                theDoc.Page = theDoc.AddPage();
                //AbcPdf cache request for 10 min consider for crucial cases.
                var theId = theDoc.AddImageHtml(customData);

                while (true)
                {
                    if (!theDoc.Chainable(theId))
                        break;
                    theDoc.Page = theDoc.AddPage();
                    theId = theDoc.AddImageToChain(theId);
                }

                // Link pages together
                theDoc.HtmlOptions.LinkPages();

                for (var i = 1; i <= theDoc.PageCount; i++)
                {
                    theDoc.PageNumber = i;
                    theDoc.Flatten();
                }

                var buffer = theDoc.GetData();
                theDoc.Clear();

                return buffer;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static byte[] PDFForHtml(string html)
        {
            // Create ABCpdf Doc object
            var doc = new Doc();
            doc.HtmlOptions.Engine = EngineType.Gecko;
            doc.HtmlOptions.ForGecko.ProcessOptions.LoadUserProfile = true;
            doc.HtmlOptions.HostWebBrowser = true;
            doc.HtmlOptions.BrowserWidth = 800;
            doc.HtmlOptions.ForGecko.InitialWidth = 800;
            // Add html to Doc
            int theID = doc.AddImageHtml(html);

            // Loop through document to create multi-page PDF
            while (true)
            {
                if (!doc.Chainable(theID))
                    break;
                doc.Page = doc.AddPage();
                theID = doc.AddImageToChain(theID);

            }

            // Flatten the PDF
            for (int i = 1; i <= doc.PageCount; i++)
            {
                doc.PageNumber = i;
                doc.Flatten();
            }

            // Get PDF as byte array. Couls also use .Save() to save to disk
            var pdfbytes = doc.GetData();

            doc.Clear();

            return pdfbytes;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int      estimateNumber;
            int      revisionNumberA;
            int      revisionNumberB;
            string   revisionTypeA;
            string   revisionTypeB;
            string   customerDocumentA;
            string   customerDocumentB;
            DateTime effectiveDateA;
            DateTime effectiveDateB;
            decimal  homePriceA;
            decimal  homePriceB;
            decimal  upgradeValueA;
            decimal  upgradeValueB;
            decimal  siteworkValueA;
            decimal  siteworkValueB;
            decimal  totalPriceA;
            decimal  totalPriceB;
            string   revisionTitleA;
            string   revisionTitleB;
            string   statusA;
            string   statusB;
            string   ownerA;
            string   ownerB;
            string   customer;
            string   address;
            string   lotAddress;
            string   houseAndLandPackage;
            string   houseName;


            if (Page.Request.QueryString["filter"] != null && Page.Request.QueryString["filter"].ToString() != "")
            {
                filterlist = Page.Request.QueryString["filter"].ToString();
            }

            int estimateRevisionIdA = 0;
            int estimateRevisionIdB = 0;

            int.TryParse(Request.QueryString["Source"], out estimateRevisionIdA);
            int.TryParse(Request.QueryString["Destination"], out estimateRevisionIdB);

            GetEstimateHeader(estimateRevisionIdA, out estimateNumber, out revisionTypeA, out revisionNumberA, out effectiveDateA, out homePriceA, out upgradeValueA, out siteworkValueA, out totalPriceA, out ownerA, out statusA, out houseName, out customer, out houseAndLandPackage, out customerDocumentA);
            GetEstimateHeader(estimateRevisionIdB, out estimateNumber, out revisionTypeB, out revisionNumberB, out effectiveDateB, out homePriceB, out upgradeValueB, out siteworkValueB, out totalPriceB, out ownerB, out statusB, out houseName, out customer, out houseAndLandPackage, out customerDocumentB);

            GetEstimateInformation(estimateNumber, out lotAddress, out address);

            revisionTitleA = "Revision " + revisionNumberA.ToString() + " (" + revisionTypeA + ")";
            if (!string.IsNullOrEmpty(customerDocumentA))
            {
                revisionTitleA += " - " + customerDocumentA;
            }

            revisionTitleB = "Revision " + revisionNumberB.ToString() + " (" + revisionTypeB + ")";
            if (!string.IsNullOrEmpty(customerDocumentB))
            {
                revisionTitleB += " - " + customerDocumentB;
            }

            Doc theDoc = new Doc();

            theDoc.MediaBox.SetRect(0, 0, 842, 595);
            theDoc.Rect.String = "30 35 812 565";

            string docBody = @"
<html>
<head>
    <title></title>
    <style type='text/css'>
    body 
    {
        font-family:Tahoma, Verdana, Arial;
        font-size: 10px;
    }
    table
    {
        border-color:#6699CC;
        border-width:0 0 1px 1px;
        border-style:solid;
    }
    td
    {
        border-color:#6699CC;
        border-width:1px 1px 0 0;
        border-style:solid;
        padding:4px;
        margin:0;
        font-family:Tahoma, Verdana, Arial;
        font-size: 10px;
    }
    .SummaryTable
    {
        border-style:none;
    }
    .TableHeader
    {
        background-color:#AFEEEE;
        text-align:center;
    }
    .SourceRevision
    {
        background-color:#F0F8FF;
    }
    .DestinationRevision
    {
        background-color:#F5F5DC;
    }
    </style>
</head>
<body>
    <table border='0' class='SummaryTable'>
        <tr>
            <td colspan='2' class='SummaryTable'><b>Estimate " + estimateNumber.ToString() + @" Comparison</b>&nbsp;&nbsp;&nbsp;&nbsp;Source: " + revisionTitleA + @"&nbsp;&nbsp;&nbsp;&nbsp;Destination: " + revisionTitleB + @"<br /></td>
        </tr>
        <tr>
            <td class='SummaryTable'>Customer:</td>
            <td class='SummaryTable'>" + customer + @"</td>
        </tr>
        <tr>
            <td class='SummaryTable'>Correspondence Address:</td>
            <td class='SummaryTable'>" + address + @"</td>
        </tr>
        <tr>
            <td class='SummaryTable'>Lot Address:</td>
            <td class='SummaryTable'>" + lotAddress + @"</td>
        </tr>
        <tr>
            <td class='SummaryTable'>House and Land Package:</td>
            <td class='SummaryTable'>" + houseAndLandPackage + @"</td>
        </tr>
        <tr>
            <td class='SummaryTable'>House Name:</td>
            <td class='SummaryTable'>" + houseName + @"</td>
        </tr>
    </table>
    <br />
    <table cellpadding='0' cellspacing='0' width='100%'>
        <tr>
            <td colspan='3' class='TableHeader'>Estimate Header</td>
        </tr>
        <tr>
            <td width='280' class='TableHeader'>Field</td>
            <td width='280' class='TableHeader'>" + revisionTitleA + @"</td>
            <td width='280' class='TableHeader'>" + revisionTitleB + @"</td>
        </tr>
        <tr>
            <td>Price Effective Date</td>
            <td class='SourceRevision'>" + effectiveDateA.ToString("dd/MM/yyyy") + @"</td>
            <td class='DestinationRevision'>" + effectiveDateB.ToString("dd/MM/yyyy") + @"</td>
        </tr>
        <tr>
            <td>Home Price</td>
            <td class='SourceRevision'>" + homePriceA.ToString("c") + @"</td>
            <td class='DestinationRevision'>" + homePriceB.ToString("c") + @"</td>
        </tr>
        <tr>
            <td>Upgrade Value</td>
            <td class='SourceRevision'>" + upgradeValueA.ToString("c") + @"</td>
            <td class='DestinationRevision'>" + upgradeValueB.ToString("c") + @"</td>
        </tr>
        <tr>
            <td>Site Work Value</td>
            <td class='SourceRevision'>" + siteworkValueA.ToString("c") + @"</td>
            <td class='DestinationRevision'>" + siteworkValueB.ToString("c") + @"</td>
        </tr>
        <tr>
            <td>Total Price</td>
            <td class='SourceRevision'>" + totalPriceA.ToString("c") + @"</td>
            <td class='DestinationRevision'>" + totalPriceB.ToString("c") + @"</td>
        </tr>
        <tr>
            <td>Status</td>
            <td class='SourceRevision'>" + statusA + @"</td>
            <td class='DestinationRevision'>" + statusB + @"</td>
        </tr>
        <tr>
            <td>Owner</td>
            <td class='SourceRevision'>" + ownerA + @"</td>
            <td class='DestinationRevision'>" + ownerB + @"</td>
        </tr>
    </table> 
    <br />
    <table cellpadding='0' cellspacing='0' width='840'>
        <tr>
            <td colspan='11' class='TableHeader'>Estimate Details</td>
        </tr>
        <tr>
            <td  class='TableHeader'>&nbsp;</td>
            <td colspan='4' class='TableHeader'>" + revisionTitleA + @"</td>
            <td colspan='4' class='TableHeader'>" + revisionTitleB + @"</td>
            <td class='TableHeader'>&nbsp;</td>
        </tr>
        <tr>
            <td class='SourceRevision' width='40'>Area/Group</td>
            <td class='SourceRevision' width='290'>Product Description</td>
            <td class='SourceRevision' width='20'>UOM</td>
            <td class='SourceRevision' width='30'>Qty</td>
            <td class='SourceRevision' width='45'>Price</td>
            <td class='DestinationRevision' width='290'>Product Description</td>
            <td class='DestinationRevision' width='20'>UOM</td>
            <td class='DestinationRevision' width='30'>Qty</td>
            <td class='DestinationRevision' width='45'>Price</td>
            <td width='30'>Changes</td>
        </tr>" + GetDetailsComparisonContent(estimateRevisionIdA, estimateRevisionIdB) + @"</table> 
</body>
</html>";

            int theID = theDoc.AddImageHtml(docBody);

            while (theDoc.Chainable(theID))
            {
                theDoc.Page = theDoc.AddPage();
                theID       = theDoc.AddImageToChain(theID);
            }

            Random R = new Random();

            byte[] theData = theDoc.GetData();
            Response.Clear();
            Response.AddHeader("content-type", "application/pdf");
            Response.AddHeader("content-disposition", "inline; filename='EstimateComparison" + "_" + R.Next(1000).ToString() + ".pdf'");

            if (Context.Response.IsClientConnected)
            {
                Context.Response.OutputStream.Write(theData, 0, theData.Length);
                Context.Response.Flush();
            }

            theDoc.Clear();
        }
        protected Doc AssessmentSummaryToPdfDoc(PdfRenderSettings settings = null)
        {
            var dp = DistrictParms.LoadDistrictParms();
            if (settings == null) settings = new PdfRenderSettings();

            StringWriter sw = new StringWriter();
            HtmlTextWriter w = new HtmlTextWriter(sw);
            summaryContent.Attributes["style"] = "font-family: Sans-Serif, Arial;font-weight: bold;position: relative;font-size: .8em;";
            summaryContent.RenderControl(w);
            string result_html = sw.GetStringBuilder().ToString();

            int topOffset = settings.HeaderHeight > 0 ? settings.HeaderHeight : 0;
            int bottomOffset = settings.FooterHeight > 0 ? settings.FooterHeight : 0;

            Doc doc = new Doc();
            doc.HtmlOptions.HideBackground = true;
            doc.HtmlOptions.PageCacheEnabled = false;
            doc.HtmlOptions.UseScript = true;
            doc.HtmlOptions.Timeout = 36000;
            doc.HtmlOptions.BreakZoneSize = 100;    // I experiemented with this being 99% instead of 100%, but you end up with passages getting cut off in unflattering ways. This may lead to more blank space... but I think it's the lessor of evils
            doc.HtmlOptions.ImageQuality = 70;

            doc.MediaBox.String = "0 0 " + settings.PageWidth + " " + settings.PageHeight;
            doc.Rect.String = settings.LeftMargin + " " + (0 + bottomOffset).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + (settings.PageHeight - topOffset).ToString();
            doc.HtmlOptions.AddTags = true;
            doc.SetInfo(0, "ApplyOnLoadScriptOnceOnly", "1");

            List<int> forms = new List<int>();

            int theID = doc.AddImageHtml(result_html);

            Thinkgate.Base.Classes.Assessment.ChainPDFItems(doc, theID, forms, settings, dp.PdfPrintPageLimit); 

            if (settings.HeaderHeight > 0 && !String.IsNullOrEmpty(settings.HeaderText))
            {
                /*HttpServerUtility Server = HttpContext.Current.Server;
                headerText = Server.HtmlDecode(headerText);*/
                Doc headerDoc = new Doc();

                headerDoc.MediaBox.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                headerDoc.Rect.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                headerDoc.VPos = 0.5;
                int headerID = headerDoc.AddImageHtml(settings.HeaderText);

                if (!String.IsNullOrEmpty(settings.HeaderText))
                {
                    int form_ref = 0;
                    for (int i = 1; i <= doc.PageCount; i++)
                    {
                        if (form_ref < forms.Count && forms[form_ref] == i)
                        {
                            form_ref++;
                        }
                        else
                        {
                            if (i > 1 || settings.ShowHeaderOnFirstPage)
                            {
                                doc.PageNumber = i;
                                doc.Rect.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                                doc.VPos = 0.5;

                                theID = doc.AddImageDoc(headerDoc, 1, null);
                                theID = doc.AddImageToChain(theID);
                            }
                        }
                    }
                }
            }

            for (int i = 1; i <= doc.PageCount; i++)
            {
                doc.PageNumber = i;
                doc.Flatten();
            }
            return doc;
        }
Пример #20
0
		private void ConvertHTMLToPDF(string htmlString, string fullPDFFilePath)
		{
			Doc theDoc = new Doc();

            //theDoc.HtmlOptions.Engine = EngineType.Gecko;
			
			theDoc.Rect.Inset(8, 8);

			int theID = theDoc.AddImageHtml(htmlString, true, 0, true);
		
			while (true) 
			{
				//theDoc.FrameRect();
				if (theDoc.GetInfo(theID, "Truncated") != "1")
					break;
				theDoc.Page = theDoc.AddPage();
				theID = theDoc.AddImageToChain(theID);
			}

			for (int i = 1; i <= theDoc.PageCount; i++) 
			{
				theDoc.PageNumber = i;
				theDoc.Flatten();
			}

			if (File.Exists(fullPDFFilePath))
				File.Delete(fullPDFFilePath);

			theDoc.Save(fullPDFFilePath);
			theDoc.Clear();
		}
        protected Doc ItemAnalysisToPdfDoc(PdfRenderSettings settings = null)
        {
            if (settings == null) settings = new PdfRenderSettings();

            StringWriter sw = new StringWriter();
            HtmlTextWriter w = new HtmlTextWriter(sw);
            reportHeaderDiv.Controls.Add(LoadPDFHeaderInfo());
            barGraphLevelsContainerDiv.Controls.Add(LoadBarGraphLevels());
            barGraphPDFContainerDiv.Controls.Add(LoadBarGraphs());
            contentDiv.RenderControl(w);
            string result_html = sw.GetStringBuilder().ToString();

            int topOffset = settings.HeaderHeight > 0 ? settings.HeaderHeight : 0;
            int bottomOffset = settings.FooterHeight > 0 ? settings.FooterHeight : 0;

            Doc doc = new Doc();
            doc.HtmlOptions.HideBackground = true;
            doc.HtmlOptions.PageCacheEnabled = false;
            doc.HtmlOptions.UseScript = true;
            doc.HtmlOptions.Timeout = 36000;
            doc.HtmlOptions.BreakZoneSize = 100;    // I experiemented with this being 99% instead of 100%, but you end up with passages getting cut off in unflattering ways. This may lead to more blank space... but I think it's the lessor of evils
            doc.HtmlOptions.ImageQuality = 70;

            doc.MediaBox.String = "0 0 " + settings.PageWidth + " " + settings.PageHeight;
            doc.Rect.String = settings.LeftMargin + " " + (0 + bottomOffset).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + (settings.PageHeight - topOffset).ToString();
            doc.HtmlOptions.AddTags = true;
            doc.SetInfo(0, "ApplyOnLoadScriptOnceOnly", "1");

            List<int> forms = new List<int>();

            int theID = doc.AddImageHtml(result_html);

            while (true)
            {
                if (!doc.Chainable(theID))
                    break;
                doc.Page = doc.AddPage();
                theID = doc.AddImageToChain(theID);
                string[] tagIds = doc.HtmlOptions.GetTagIDs(theID);
                if (tagIds.Length > 0 && tagIds[0] == "test_header")
                    forms.Add(doc.PageNumber);					// By using GetTagIDs to find if a test header ended up on this page, we can determine whether the page needs a header

                if (settings.PossibleForcedBreaks)
                {		// only want to take the performance hit if there's a change we're forcing breaks
                    if (String.IsNullOrEmpty(doc.GetText("Text")))
                    {		// WSH Found situation where after I added page break always for multi-form, one test that was already breaking properly, added an extra page that was blank between forms. Almost like some amount of HTML had been put there, even though it wasn't any real text. By checking to make sure there is some actual text on page, we can avoid that problem
                        doc.Delete(doc.Page);
                    }
                }
            }

            if (settings.HeaderHeight > 0 && !String.IsNullOrEmpty(settings.HeaderText))
            {
                /*HttpServerUtility Server = HttpContext.Current.Server;
                headerText = Server.HtmlDecode(headerText);*/
                Doc headerDoc = new Doc();

                headerDoc.MediaBox.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                headerDoc.Rect.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                headerDoc.VPos = 0.5;
                int headerID = headerDoc.AddImageHtml(settings.HeaderText);

                if (!String.IsNullOrEmpty(settings.HeaderText))
                {
                    int form_ref = 0;
                    for (int i = 1; i <= doc.PageCount; i++)
                    {
                        if (form_ref < forms.Count && forms[form_ref] == i)
                        {
                            form_ref++;
                        }
                        else
                        {
                            if (i > 1 || settings.ShowHeaderOnFirstPage)
                            {
                                doc.PageNumber = i;
                                doc.Rect.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                                doc.VPos = 0.5;

                                theID = doc.AddImageDoc(headerDoc, 1, null);
                                theID = doc.AddImageToChain(theID);
                            }
                        }
                    }
                }
            }

            for (int i = 1; i <= doc.PageCount; i++)
            {
                doc.PageNumber = i;
                doc.Flatten();
            }
            return doc;
        }