Esempio n. 1
0
        public async Task CreateFrontPageSection(string htmlPath)
        {
            try
            {
                int theID;

                theDoc.Rect.String = "40 70 570 700";
                theID = theDoc.AddImageUrl(htmlPath);

                theDoc.Color.String = "0 255 0";
                while (true)
                {
                    if (!theDoc.Chainable(theID))
                    {
                        theID = theDoc.AddImageToChain(theID);
                        break;
                    }
                    theDoc.Page = theDoc.AddPage();
                    theID       = theDoc.AddImageToChain(theID);
                }
                await Task.FromResult(0);

                return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Enter the name of the output pdf file:");

            var fileName = System.Console.ReadLine();
            fileName = fileName.Replace(".pdf", "");
            fileName = fileName.Replace(".PDF", "");

            Doc theDoc = new Doc();
            theDoc.Rect.Inset(72, 144);
            theDoc.HtmlOptions.AddLinks = true;

            int theID;
            theID = theDoc.AddImageUrl("http://www.yahoo.com/");

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

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

            theDoc.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName + ".pdf"));
            theDoc.Clear();
        }
Esempio n. 3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        byte[] pdfData;
        var    url = Web.BaseUrl;

        using (var theDoc = new Doc()) {
            theDoc.MediaBox.String = "A4";                     // this sets the page to A4 (also removes scrollbar showing in the pdf LOL)
            theDoc.TopDown         = true;
            theDoc.Rect.Top        = 5;
            theDoc.Rect.Left       = -18;
            //clear caching?
            //theDoc.HtmlOptions.Engine = EngineType.Gecko;
            theDoc.HtmlOptions.PageCacheEnabled = false;
            theDoc.HtmlOptions.UseNoCache       = true;
            theDoc.HtmlOptions.PageCacheClear();
            theDoc.HtmlOptions.PageCachePurge();
            theDoc.HtmlOptions.UseResync = true;
            theDoc.HtmlOptions.Timeout   = 30 * 1000;                   // 30 seconds
            var id = theDoc.AddImageUrl(url);
            //add more pages if more than 1 page
            for (; theDoc.Chainable(id);)
            {
                theDoc.Page = theDoc.AddPage();
                id          = theDoc.AddImageToChain(id);
            }
            //theDoc.Save(fullServerPath);
            pdfData = theDoc.GetData();
            Web.Response.ContentType = "application/pdf";
            Web.Response.BinaryWrite(pdfData);
            theDoc.Clear();
        }
    }
        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);
        }
Esempio n. 5
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);
        }
Esempio n. 6
0
    protected void btnGenerarActas_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                string       codigo = ((Label)row.FindControl("IdCoordinacion")).Text;
                Coordinacion obj    = DatosCoordinacion.BuscarCoordinacion(Convert.ToInt32(codigo));
                //Session["CodigoObs"] = codigo;

                Doc documento = new Doc();

                //documento.Page = documento.AddPage();

                int id = 0;

                string url = "http://localhost:15674/InformeActasPDF.aspx" + "?CodigoObs=" + codigo + "-" + obj.Fecha;

                //string url = "http://localhost:15674/Constructora/InformeActa.aspx";

                documento.HtmlOptions.PageCacheClear();
                documento.HtmlOptions.PageCachePurge();

                documento.HtmlOptions.Paged = true;
                documento.Page = documento.AddPage();

                id = documento.AddImageUrl(url);


                while (true)
                {
                    documento.FrameRect();
                    if (!documento.Chainable(id))
                    {
                        break;
                    }
                    documento.Page = documento.AddPage();
                    id             = documento.AddImageToChain(id);
                }

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

                documento.Save("C:/GeneracionActas/" + codigo + ".pdf");
                documento.Clear();
            }
        }
        catch (Exception ex)
        {
            lblMensaje.Text = ex.Message;
        }
    }
Esempio n. 7
0
    protected void printbutton_Click(object sender, EventArgs e)
    {
        string contents = string.Empty;

        MemoryStream ms = new MemoryStream();
        //using (StringWriter sw = new StringWriter()) {
        //    Server.Execute("Documents/report.aspx", sw);
        //    contents = sw.ToString();
        //    sw.Close();
        //}

        try {

            Doc doc = new Doc();
            //int font = doc.EmbedFont(Server.MapPath("Documents/") + "OpenSans-Regular-webfont.ttf", LanguageType.Unicode);
            //font = doc.EmbedFont(Server.MapPath("Documents/") + "OpenSans-Light-webfont.ttf", LanguageType.Unicode);
            doc.HtmlOptions.BrowserWidth = 960;
            doc.HtmlOptions.FontEmbed = true;
            doc.HtmlOptions.FontSubstitute = false;
            doc.HtmlOptions.FontProtection = false;
            int id = 0;
            Random rnd = new Random();
            //id = doc.AddImageUrl("http://" + Request.Url.Host + "/documents/bygg.aspx?rnd=" + rnd.Next(50000));
            id = doc.AddImageUrl("http://localhost:50030/Documents/jour.aspx?rnd=" + rnd.Next(50000));

            while (true) {
                //doc.FrameRect();
                if (!doc.Chainable(id)) {
                    break;
                }
                doc.Page = doc.AddPage();
                id = doc.AddImageToChain(id);
            }

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

            //doc.AddImageHtml(contents);
            //doc.Save(Server.MapPath("htmlimport.pdf"));
            doc.Save(ms);
            //doc.SaveOptions.
            doc.Clear();

                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename=File-{0}.pdf", 1));
                Response.BinaryWrite(ms.ToArray());
                Response.End();

            //}
        } catch (Exception ex) {
            Response.Write(ex.Message);
        }
    }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints => {
                endpoints.MapGet("/", async context => {
                    context.Response.Clear();
                    try {
                        // When running as an App Service we need to install the license in code otherwise you will
                        // get a licensing exception. ABCpdf automatically installs a trial license if no license is
                        // found.
                        // Your trial license may be found by uncommenting the line below WHEN RUNNING ON YOUR LOCAL
                        // COMPUTER. NB XSettings.Key returns an empty string for purchased licenses.
                        // throw new Exception(XSettings.Key);

                        // Paste either the ABCpdf 12 key provided at time of purchase, or the value obtained from
                        // uncommenting the line above. This must be set correctly prior to running on Azure.
                        XSettings.InstallLicense("PASTE YOUR LICENSE HERE");

                        using (Doc doc = new Doc()) {
                            doc.HtmlOptions.Engine = EngineType.WebKit;
                            doc.HtmlOptions.Media  = MediaType.Screen;
                            int id = doc.AddImageUrl("https://www.websupergoo.com");

                            // AddImageUrl only adds the first page. The following code adds any additional pages:
                            while (doc.Chainable(id))
                            {
                                doc.Page = doc.AddPage();
                                id       = doc.AddImageToChain(id);
                            }
                            // Compress output:
                            for (int i = 1; i <= doc.PageCount; i++)
                            {
                                doc.PageNumber = i;
                                doc.Flatten();
                            }
                            // This will ensure page is served in a web-efficient manner:
                            doc.SaveOptions.Linearize = true;
                            // Finally serve the page:
                            context.Response.ContentType = "Application/Pdf";
                            await context.Response.BodyWriter.WriteAsync(doc.GetData());
                        }
                    } catch (Exception ex) {
                        await context.Response.WriteAsync(ex.Message);
                    }
                    await context.Response.CompleteAsync();
                });
            });
        }
    public static bool createPdf(long kid,string klotterno,string email)
    {
        string contents = string.Empty;

        MemoryStream ms = new MemoryStream();

        try {
            int id;
            Doc doc = new Doc();

            doc.MediaBox.String = "A4";
            doc.Rect.String = doc.MediaBox.String;
            //doc.Rect. = doc.CropBox;
            doc.HtmlOptions.BrowserWidth = 980;
            doc.HtmlOptions.FontEmbed = true;
            doc.HtmlOptions.FontSubstitute = false;
            doc.HtmlOptions.FontProtection = false;
            doc.HtmlOptions.ImageQuality = 33;
            Random rnd = new Random();
            id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/klotter_pdf.aspx?id=" + kid.ToString() + "&uid="+ email +"&rnd=" + rnd.Next(50000));

            while (true) {
                //doc.FrameRect();
                if (!doc.Chainable(id)) {
                    break;
                }
                doc.Page = doc.AddPage();
                id = doc.AddImageToChain(id);
            }

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

            //doc.AddImageHtml(contents);
            //doc.Save(Server.MapPath("htmlimport.pdf"));
            doc.Save(ms);
            //doc.SaveOptions.
            doc.Clear();

            bool mail = Common.PdfMail(ms, email, "Klotter");
            if (mail) {
                return AmazonHandler.PutPdfKlotter(ms, klotterno, 0);
            }
            return false;

            //}
        } catch (Exception ex) {
            return false;
        }
    }
Esempio n. 10
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);
            }
        }
        protected void btnPrintBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            int credentialID = Convert.ToInt32(Request.QueryString["credentialID"]);
            Doc theDoc = new Doc();
            //clear caching?
            theDoc.HtmlOptions.PageCacheEnabled = false;
            theDoc.HtmlOptions.UseNoCache = true;
            theDoc.HtmlOptions.PageCacheClear();
            theDoc.HtmlOptions.PageCachePurge();
            theDoc.HtmlOptions.UseResync = true;
            theDoc.Rect.String = "10 90 600 750";




            string selectedCriteria = Session["selectedCriteria"].ToString();

            string hostURL = (HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://") + HttpContext.Current.Request.Url.Host.ToString();
            string callUrl = ResolveUrl("~/Controls/Credentials/PDF/StudentCountListPdf.aspx?xCriteria=" + selectedCriteria);
            int theID;
            theID = theDoc.AddImageUrl(hostURL + callUrl);
            while (true)
            {

                if (!theDoc.Chainable(theID))
                    break;
                theDoc.Page = theDoc.AddPage();
                theID = theDoc.AddImageToChain(theID);
            }
            for (int i = 1; i <= theDoc.PageCount; i++)
            {
                theDoc.PageNumber = i;

                theDoc.Flatten();
            }
            theDoc = AddHeaderFooter(theDoc);
            byte[] pdf = theDoc.GetData();

            Response.Clear();
            Response.ClearHeaders();    // Add this line
            Response.ClearContent();    // Add this line
            //string filename = lblStudentName.Text.Replace(',', '-') + "EarnedCredentialList";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + "CredentialList" + ".pdf");
            Response.AddHeader("content-length", pdf.Length.ToString());
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(pdf);
            Response.End();
            theDoc.Clear();

        }
Esempio n. 12
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);
        }
Esempio n. 13
0
        private Stream ConvertUrlToImage(string url, int marginLeft, int marginTop, int page)
        {
            //bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]);

            MemoryStream memoryStream = null;

            byte[] imageBytes = null;
            //return the coresponding image here for the first page
            XSettings.InstallRedistributionLicense(
                System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]);

            //Create a new Doc
            using (Doc theDoc = new Doc())
            {
                theDoc.HtmlOptions.UseScript  = true; // Enable javascript at the startup time
                theDoc.HtmlOptions.UseActiveX = true; // Enable SVG
                theDoc.HtmlOptions.UseVideo   = true; // Enable Video
                theDoc.HtmlOptions.Timeout    = 120000;
                // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html
                theDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache
                theDoc.Rect.Inset(marginLeft, marginTop);   // Insert the margin left and margin top
                theDoc.Page = theDoc.AddPage();

                int theID = theDoc.AddImageUrl(url.ToString());
                // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                while (true)
                {
                    if (!theDoc.Chainable(theID))
                    {
                        break;
                    }
                    theDoc.Page = theDoc.AddPage();
                    theDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150
                    theDoc.Rendering.SaveQuality = constSaveQuality;  // set Quality = 100
                    theID = theDoc.AddImageToChain(theID);
                }
                theDoc.PageNumber            = page;
                theDoc.Rendering.DotsPerInch = constDotPerInches;
                theDoc.Rendering.SaveQuality = constImageQuality;
                theDoc.Flatten();
                imageBytes = theDoc.Rendering.GetData("abc.png");
                theDoc.Clear();
            }
            memoryStream = new MemoryStream(imageBytes);

            return(memoryStream);
        }
Esempio n. 14
0
        public byte[] Convert(string link)
        {
            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.HtmlOptions.AddMovies = true;
                theDoc.Page = theDoc.AddPage();
                theDoc.HtmlOptions.PageCacheEnabled = false;

                var theId = theDoc.AddImageUrl(link);

                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;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 整个任务书展示页面生成pdf,同时计算页码,生成书签(此方法不完善,书签定位不正确)
        /// </summary>
        /// <param name="docList"></param>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        /// <param name="customName"></param>
        /// <param name="tops"></param>
        /// <returns></returns>
        public static bool MergePdf3(List <PdfDoc> docList, string url, string savePath, string customName, Dictionary <int, int> tops)
        {
            Doc doc = new Doc();

            doc.HtmlOptions.Timeout          = 30 * 1000;
            doc.HtmlOptions.UseScript        = true;
            doc.HtmlOptions.UseNoCache       = true;
            doc.HtmlOptions.PageCacheEnabled = false;
            doc.HtmlOptions.PageCacheClear();

            int num = doc.AddImageUrl(url);

            while (true)
            {
                if (!doc.Chainable(num))
                {
                    break;
                }
                doc.Page = doc.AddPage();
                num      = doc.AddImageToChain(num);
            }
            for (int i = 0; i < tops.Count; i++)
            {
                int    minusOffset = tops.Values.ToList <int>()[0] * i;
                double offset      = 0.0;
                doc.PageNumber = CalculatePageNum(doc, tops.Values.ToList <int>()[i], out offset, minusOffset);
                int id = doc.AddBookmark(GetPath(docList, tops.Keys.ToList <int>()[i]).TrimEnd('\\'), true);
                doc.SetInfo(id, "/Dest:Del", "");
                doc.SetInfo(id, "/Dest[]:Ref", doc.Page.ToString());
                doc.SetInfo(id, "/Dest[]:Name", "XYZ");
                doc.SetInfo(id, "/Dest[]:Num", "0");
                doc.SetInfo(id, "/Dest[]:Num", offset.ToString());
                doc.SetInfo(id, "/Dest[]", "null");
            }

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

            return(true);
        }
Esempio n. 16
0
        /// <summary>
        /// CreatePDF :Public method used to create PDF file
        /// </summary>
        /// <param name="SourceFilePath">SourceFilePath Datatype:String </param>
        /// <param name="DestinationFilePath">DestinationFilePath Datatype:String</param>
        public void CreatePDF(string SourceFilePath, string DestinationFilePath)
        {
            //
            // Initialize required variables
            //
            string theURL = string.Empty;
            int    theID;

            //
            // Create Pdf using the source file as input
            //
            Doc theDoc = new Doc();

            //theDoc.Rect.Inset(120, 100);
            theDoc.Page = theDoc.AddPage();

            theID = theDoc.AddImageUrl(SourceFilePath);

            //
            // Loop through and add all the html files
            //
            while (true)
            {
                theDoc.FrameRect(); // add a black border
                if (!theDoc.Chainable(theID))
                {
                    break;
                }
                theDoc.Page = theDoc.AddPage();
                theID       = theDoc.AddImageToChain(theID);
            }

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

            //
            // Now save the pdf file
            //
            theDoc.Save(DestinationFilePath);
            theDoc.Clear();
        }
Esempio n. 17
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());
        }
Esempio n. 18
0
        /// <summary>
        /// 将html页面生成pdf文档,异步方式
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static bool Html2Img(string url, string originPath)
        {
            Thread newThread = new Thread(delegate()
            {
                try
                {
                    Doc doc = new Doc();
                    doc.HtmlOptions.Timeout   = 30 * 1000;
                    doc.HtmlOptions.UseScript = true;
                    doc.Rect.Inset(36.0, 72.0);
                    doc.Page = doc.AddPage();
                    int num  = doc.AddImageUrl(url);
                    while (true)
                    {
                        doc.FrameRect();
                        if (!doc.Chainable(num))
                        {
                            break;
                        }
                        doc.Page = doc.AddPage();
                        num      = doc.AddImageToChain(num);
                    }
                    for (int i = 1; i <= doc.PageCount; i++)
                    {
                        doc.PageNumber = i;
                        doc.Flatten();
                    }
                    doc.Save(originPath);
                    doc.Clear();
                }
                catch (Exception ex)
                {
                    LogError.ReportErrors(ex.Message);
                }
            });

            newThread.Start();

            return(true);
        }
Esempio n. 19
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);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Enter the name of the output pdf file:");

            var fileName = System.Console.ReadLine();

            fileName = fileName.Replace(".pdf", "");
            fileName = fileName.Replace(".PDF", "");

            Doc theDoc = new Doc();

            theDoc.Rect.Inset(72, 144);
            theDoc.HtmlOptions.AddLinks = true;

            int theID;

            theID = theDoc.AddImageUrl("http://www.yahoo.com/");

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

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

            theDoc.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName + ".pdf"));
            theDoc.Clear();
        }
        /// <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();
        }
        /// <summary>
        /// Convert the HTML code from the specified URL to a PDF document and send the 
        /// document as an attachment to the browser
        /// </summary>
        /// <param name="sessionTokenId">SessionTokenId given by user to authorize</param>
        /// <param name="url">The URL of a page that will be rendered</param>
        /// <param name="marginLeft"></param>
        /// <param name="marginTop"></param>
        /// <returns>a byte array that rendered as a PDF, will be null if error</returns>
        Stream IPrintServiceV1.ConvertUrlToPdf(string sessionTokenId, string url, int marginLeft, int marginTop)
        {
            Stream returnStream = null;

            if (marginLeft < 10000 && marginTop < 10000)
            {
                try
                {
                    bool isQualified = IsQualifiedUrl(url.ToString());
                    if (isQualified)
                    {
                        // Create a Doc object
                        XSettings.InstallRedistributionLicense(licenseKey);

                        using (Doc theDoc = new Doc())
                        {
                            //theDoc.SetInfo(0, "RenderDelay", "1000");
                            theDoc.HtmlOptions.UseScript = true;
                            theDoc.HtmlOptions.UseActiveX = true;
                            theDoc.HtmlOptions.UseVideo = true;
                            theDoc.HtmlOptions.PageCacheEnabled = true;
                            theDoc.HtmlOptions.Timeout = 120000; // 120 seconds
                            theDoc.Rect.Inset(marginLeft, marginTop); // add margin

                            // Add the first page of HTML. Save the returned ID as this will be used to add subsequent pages
                            theDoc.Page = theDoc.AddPage();

                            int theID = theDoc.AddImageUrl(url.ToString());

                            // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                            while (true)
                            {
                                if (!theDoc.Chainable(theID))
                                    break;
                                theDoc.Page = theDoc.AddPage();
                                theDoc.Rendering.DotsPerInch = constDotPerInches; // DPI
                                theDoc.Rendering.SaveQuality = constSaveQuality; // Quality
                                theID = theDoc.AddImageToChain(theID);
                            }

                            // 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 (int i = 1; i <= theDoc.PageCount; i++)
                            {
                                theDoc.PageNumber = i;
                                theDoc.Flatten();
                            }
                            // Get pdf data from the Doc object
                            returnStream = new MemoryStream(theDoc.GetData());
                            //returnByte = theDoc.GetData();

                            theDoc.Clear();
                        }
                    }

                    //TO-DO: Add the HTTP Status Code 403 (Forbidden) when the url is not in supported list
                }
                catch (UriFormatException uriFormatException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName,
                                         uriFormatException.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + uriFormatException.Message +
                                         uriFormatException.StackTrace);
                    returnStream = null;
                }
                catch (WebException webException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, webException.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + webException.Message +
                                         webException.StackTrace);
                    returnStream = null;
                }
                catch (Exception ex)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + ex.Message + ex.StackTrace);
                    returnStream = null;
                }
                if (WebOperationContext.Current != null)
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
                    HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                    WebOperationContext.Current.OutgoingResponse.Headers.Add(cacheHeader,
                                                                             string.Format(CultureInfo.InvariantCulture,
                                                                                           "max-age={0}, must-revalidate",
                                                                                           CachingDuration));
                    //Add one day caching
                }
            }
            return returnStream;
        }
Esempio n. 23
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);
            }
        }
Esempio n. 24
0
        public void GeneratePdf(string pageurl, string fileSavePath, bool showFooterText = false, string footerText = "", string coverSheetPages = "", string customizedLetter = "", string contentpages = "", string kynFile = "", string bloodLetter = "",
                                string doctorLetter   = "", string corporateFluffLetter = "", bool isPpCustomer        = false, string awvTestResult = "", bool isPcpReport = false, bool generatePcpLetter = false, string scannedDocumentsPdf = "", string eawvPdfReport = "",
                                string focAttestation = "", string attestationForm      = "", bool hasSectionToDisplay = true, string mammogram      = "", string ifobt     = "", string urineMicroalbumin  = "", string participantLetter      = "", string chlamydia = "",
                                string awvBoneMass    = "", string osteoporosis         = "", string quantaFloAbi      = "", string hkyn = "", string mybioCheckAssessment  = "", string memberLetter = "", string greenFormAttestation = "", string dpn               = "")
        {
            var finalReport = new Doc();

            int prePrintedCount = 0;

            var beforFinalReportDoc = new Doc();

            try
            {
                if (coverSheetPages != "")
                {
                    var participantLetterDoc = new Doc();
                    var doctorLetterDoc      = new Doc();
                    var customizedLetterDoc  = new Doc();
                    var contentpagesDoc      = new Doc();
                    var eawvPdfDoc           = new Doc();

                    var memberLetterDoc         = new Doc();
                    var greenFormAttestationDoc = new Doc();
                    try
                    {
                        //Cover Sheet
                        beforFinalReportDoc.Read(coverSheetPages);

                        if (!string.IsNullOrWhiteSpace(greenFormAttestation))
                        {
                            greenFormAttestationDoc.Read(greenFormAttestation);
                            beforFinalReportDoc.Append(greenFormAttestationDoc);
                        }

                        //Member Letter
                        if (!string.IsNullOrEmpty(memberLetter))
                        {
                            memberLetterDoc.Read(memberLetter);
                            beforFinalReportDoc.Append(memberLetterDoc);
                        }

                        if (!string.IsNullOrEmpty(participantLetter))
                        {
                            participantLetterDoc.Read(participantLetter);
                            beforFinalReportDoc.Append(participantLetterDoc);
                        }

                        //Doctor letter
                        if (!string.IsNullOrEmpty(doctorLetter))
                        {
                            doctorLetterDoc.Read(doctorLetter);
                            beforFinalReportDoc.Append(doctorLetterDoc);
                        }
                        //Customized Letter Hospital Partner no default letter
                        if (!string.IsNullOrEmpty(customizedLetter))
                        {
                            customizedLetterDoc.Read(customizedLetter);
                            beforFinalReportDoc.Append(customizedLetterDoc);
                        }

                        if (!string.IsNullOrEmpty(contentpages))
                        {
                            contentpagesDoc.Read(contentpages);
                            beforFinalReportDoc.Append(contentpagesDoc);
                        }

                        if (!string.IsNullOrEmpty(eawvPdfReport))
                        {
                            eawvPdfDoc.Read(eawvPdfReport);
                            beforFinalReportDoc.Append(eawvPdfDoc);
                        }

                        prePrintedCount = beforFinalReportDoc.PageCount;
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        participantLetterDoc.Clear();
                        participantLetterDoc.Dispose();

                        doctorLetterDoc.Clear();
                        doctorLetterDoc.Dispose();

                        customizedLetterDoc.Clear();
                        customizedLetterDoc.Dispose();

                        contentpagesDoc.Clear();
                        contentpagesDoc.Dispose();

                        eawvPdfDoc.Clear();
                        eawvPdfDoc.Dispose();

                        memberLetterDoc.Clear();
                        memberLetterDoc.Dispose();

                        greenFormAttestationDoc.Clear();
                        greenFormAttestationDoc.Dispose();
                    }
                }

                if (hasSectionToDisplay)
                {
                    finalReport.Rect.Inset(40, 70);
                    //pdfDoc.Rect.
                    finalReport.MediaBox.String = PaperSize;
                    finalReport.Rect.String     = finalReport.MediaBox.String;
                    finalReport.Page            = finalReport.AddPage();
                    finalReport.HtmlOptions.PageCachePurge();
                    finalReport.HtmlOptions.Timeout = 90000;


                    if (AllowLoadingJavascriptbeforePdfGenerate)
                    {
                        finalReport.HtmlOptions.UseScript = true;
                    }

                    int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true);

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

                    footerText = string.IsNullOrEmpty(footerText) ? string.Empty : footerText + " | ";
                    int pageCount = finalReport.PageCount + prePrintedCount;
                    for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++)
                    {
                        finalReport.PageNumber = pageNumber;
                        if (showFooterText)
                        {
                            int pNum = pageNumber + prePrintedCount;

                            string txt = footerText + "Page: " + pNum + " of " + pageCount;

                            finalReport.Color.String = "0 0 0"; //Dark grey text

                            finalReport.TextStyle.VPos = 0.98;
                            finalReport.TextStyle.HPos = (pageNumber % 2) == 0 ? 0.10 : 0.80;

                            finalReport.AddFont("Arial");
                            //Add the page number
                            finalReport.AddText(txt);


                            //Add a line above page number
                            finalReport.AddLine(21, 40, 590, 40);
                        }

                        //Flatten page
                        finalReport.Flatten();
                    }
                }



                if (!string.IsNullOrEmpty(kynFile))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(kynFile);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                AppendPdf(finalReport, hkyn);

                if (!string.IsNullOrEmpty(bloodLetter))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(bloodLetter);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(corporateFluffLetter))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(corporateFluffLetter);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(awvTestResult))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(awvTestResult);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(scannedDocumentsPdf))
                {
                    var inputScannedPdfDoc = new Doc();
                    try
                    {
                        inputScannedPdfDoc.Read(scannedDocumentsPdf);
                        finalReport.Append(inputScannedPdfDoc);
                    }
                    finally
                    {
                        inputScannedPdfDoc.Clear();
                        inputScannedPdfDoc.Dispose();
                    }
                }

                AppendPdf(finalReport, focAttestation);
                AppendPdf(finalReport, attestationForm);
                AppendPdf(finalReport, mammogram);
                AppendPdf(finalReport, ifobt);
                AppendPdf(finalReport, urineMicroalbumin);
                AppendPdf(finalReport, chlamydia);
                AppendPdf(finalReport, awvBoneMass);
                AppendPdf(finalReport, osteoporosis);
                AppendPdf(finalReport, quantaFloAbi);
                AppendPdf(finalReport, mybioCheckAssessment);
                AppendPdf(finalReport, dpn);

                if (coverSheetPages != "")
                {
                    try
                    {
                        beforFinalReportDoc.Append(finalReport);
                        beforFinalReportDoc.Save(fileSavePath);
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                }
                else
                {
                    finalReport.Save(fileSavePath);
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                finalReport.Clear();
                finalReport.Dispose();

                beforFinalReportDoc.Clear();
                beforFinalReportDoc.Dispose();
            }
        }
Esempio n. 25
0
        /// <summary>
        /// 将html页面生成pdf文档,同步方式
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static bool Html2PDFSynch(string url, string savePath, string customName)
        {
            Doc doc = new Doc();

            try
            {
                //url = "http://localhost:8018/PDF?returnUrl=http://localhost:8018/Material/MatList/exporttopdf?matListId=167";
                doc.HtmlOptions.UseNoCache       = true;
                doc.HtmlOptions.PageCacheEnabled = false;
                doc.HtmlOptions.PageCacheClear();
                doc.HtmlOptions.Timeout    = 30 * 1000;
                doc.HtmlOptions.UseScript  = true;
                doc.HtmlOptions.UseActiveX = true;
                doc.Rect.Inset(36.0, 72.0);
                doc.Page = doc.AddPage();
                int num = doc.AddImageUrl(url);
                while (true)
                {
                    //doc.FrameRect();//添加黑色边框
                    if (!doc.Chainable(num))
                    {
                        break;
                    }
                    doc.Page = doc.AddPage();
                    num      = doc.AddImageToChain(num);
                }
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;

                    doc.Color.String = "0 0 0";     //黑色
                    doc.AddLine(24, 750, 588, 750); //画一条分隔线

                    doc.Rect.String      = "24 12 588 40";
                    doc.HPos             = 0;
                    doc.VPos             = 0.5;
                    doc.Font             = doc.AddFont("宋体", "ChineseS");
                    doc.TextStyle.Italic = true;
                    doc.AddHtml(" <font color=\"#cccccc\">" + customName + "</font>");
                    doc.TextStyle.Italic = false;

                    doc.Rect.String  = "24 12 588 40";
                    doc.HPos         = 1.0;
                    doc.VPos         = 0.5;
                    doc.Color.String = "0 0 0"; //黑色
                    doc.AddHtml("page " + i.ToString() + "/" + doc.PageCount.ToString());
                    doc.AddLine(24, 40, 588, 40);

                    doc.Flatten();
                }
                if (!savePath.ToLower().EndsWith(".pdf"))
                {
                    savePath += ".pdf";
                }
                doc.Save(savePath);
                doc.Clear();
                return(true);
            }
            catch (Exception ex)
            {
                LogError.ReportErrors(ex.Message);

                return(false);
            }
            finally
            {
                doc.Clear();
            }

            return(true);
        }
Esempio n. 26
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();
        }
Esempio n. 27
0
    protected void printbutton_Click(object sender, EventArgs e)
    {
        //if (pdf_synced) {

        //} else {
            string contents = string.Empty;

            MemoryStream ms = new MemoryStream();

            try {

                Doc doc = new Doc();

                doc.MediaBox.String = "A4";
                doc.HtmlOptions.BrowserWidth = 980;
                doc.HtmlOptions.FontEmbed = true;
                doc.HtmlOptions.FontSubstitute = false;
                doc.HtmlOptions.FontProtection = false;
                doc.HtmlOptions.ImageQuality = 33;
                int id = 0;
                Random rnd = new Random();
                id = doc.AddImageUrl("http://" + Request.Url.Host + "/Documents/jour_pdf.aspx?id=" + jourid.ToString() + "&rnd=" + rnd.Next(50000));

                while (true) {
                    //doc.FrameRect();
                    if (!doc.Chainable(id)) {
                        break;
                    }
                    doc.Page = doc.AddPage();
                    id = doc.AddImageToChain(id);
                }

                doc.Rect.String = "10 780 595 840";
                doc.HPos = 0.5;
                doc.VPos = 0.0;
                doc.Color.String = "0 255 0";
                doc.FontSize = 36;
                for (int i = 1; i <= doc.PageCount; i++) {
                    doc.PageNumber = i;
                    id = doc.AddImageUrl("http://" + Request.Url.Host + "/Documents/header.aspx?id=" + jourid.ToString() +"&rnd=" + rnd.Next(50000));
                }

                doc.Rect.String = "10 0 585 100";
                doc.HPos = 0.5;
                doc.VPos = 1.0;
                //doc.FontSize = 36;
                //for (int i = 1; i <= doc.PageCount; i++) {
                    doc.PageNumber = 1;
                    id = doc.AddImageUrl("http://" + Request.Url.Host + "/Documents/footer.aspx?rnd=" + rnd.Next(50000));
                    //doc.AddText("Page " + i.ToString() + " of " + doc.PageCount.ToString());
                    //doc.FrameRect();
                //}

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

                //doc.AddImageHtml(contents);
                //doc.Save(Server.MapPath("htmlimport.pdf"));
                doc.Save(ms);
                //doc.SaveOptions.
                doc.Clear();

                bool success = AmazonHandler.PutPdfJour(ms, journo);

                if (success) {
                    Response.Write("SUCCESS!!!!");
                } else {
                    Response.Write("FAIL!!!!");
                }

                //}
            } catch (Exception ex) {
                Response.Write(ex.Message);
            }
        //}
    }
        private Stream ConvertUrlToImage(string url, int marginLeft, int marginTop, int page)
        {
            //bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]);

            MemoryStream memoryStream = null;
            byte[] imageBytes = null;
            //return the coresponding image here for the first page
            XSettings.InstallRedistributionLicense(
                System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]);

            //Create a new Doc
            using (Doc theDoc = new Doc())
            {
                theDoc.HtmlOptions.UseScript = true; // Enable javascript at the startup time
                theDoc.HtmlOptions.UseActiveX = true; // Enable SVG
                theDoc.HtmlOptions.UseVideo = true; // Enable Video
                theDoc.HtmlOptions.Timeout = 120000;
                // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html
                theDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache
                theDoc.Rect.Inset(marginLeft, marginTop); // Insert the margin left and margin top
                theDoc.Page = theDoc.AddPage();

                int theID = theDoc.AddImageUrl(url.ToString());
                // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                while (true)
                {
                    if (!theDoc.Chainable(theID))
                        break;
                    theDoc.Page = theDoc.AddPage();
                    theDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150
                    theDoc.Rendering.SaveQuality = constSaveQuality; // set Quality = 100
                    theID = theDoc.AddImageToChain(theID);
                }
                theDoc.PageNumber = page;
                theDoc.Rendering.DotsPerInch = constDotPerInches;
                theDoc.Rendering.SaveQuality = constImageQuality;
                theDoc.Flatten();
                imageBytes = theDoc.Rendering.GetData("abc.png");
                theDoc.Clear();
            }
            memoryStream = new MemoryStream(imageBytes);

            return memoryStream;
        }
        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 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;
        }
Esempio n. 31
0
        // Put license key to Azure setting.

        #region IPrintServiceV1 Members

        /// <summary>
        /// Convert the HTML code from the specified URL to a PDF document and send the
        /// document as an attachment to the browser
        /// </summary>
        /// <param name="sessionTokenId">SessionTokenId given by user to authorize</param>
        /// <param name="url">The URL of a page that will be rendered</param>
        /// <param name="marginLeft"></param>
        /// <param name="marginTop"></param>
        /// <returns>a byte array that rendered as a PDF, will be null if error</returns>
        Stream IPrintServiceV1.ConvertUrlToPdf(string sessionTokenId, string url, int marginLeft, int marginTop)
        {
            Stream returnStream = null;

            if (marginLeft < 10000 && marginTop < 10000)
            {
                try
                {
                    bool isQualified = IsQualifiedUrl(url.ToString());
                    if (isQualified)
                    {
                        // Create a Doc object
                        XSettings.InstallRedistributionLicense(licenseKey);

                        using (Doc theDoc = new Doc())
                        {
                            //theDoc.SetInfo(0, "RenderDelay", "1000");
                            theDoc.HtmlOptions.UseScript        = true;
                            theDoc.HtmlOptions.UseActiveX       = true;
                            theDoc.HtmlOptions.UseVideo         = true;
                            theDoc.HtmlOptions.PageCacheEnabled = true;
                            theDoc.HtmlOptions.Timeout          = 120000; // 120 seconds
                            theDoc.Rect.Inset(marginLeft, marginTop);     // add margin

                            // Add the first page of HTML. Save the returned ID as this will be used to add subsequent pages
                            theDoc.Page = theDoc.AddPage();

                            int theID = theDoc.AddImageUrl(url.ToString());

                            // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                            while (true)
                            {
                                if (!theDoc.Chainable(theID))
                                {
                                    break;
                                }
                                theDoc.Page = theDoc.AddPage();
                                theDoc.Rendering.DotsPerInch = constDotPerInches; // DPI
                                theDoc.Rendering.SaveQuality = constSaveQuality;  // Quality
                                theID = theDoc.AddImageToChain(theID);
                            }

                            // 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 (int i = 1; i <= theDoc.PageCount; i++)
                            {
                                theDoc.PageNumber = i;
                                theDoc.Flatten();
                            }
                            // Get pdf data from the Doc object
                            returnStream = new MemoryStream(theDoc.GetData());
                            //returnByte = theDoc.GetData();

                            theDoc.Clear();
                        }
                    }

                    //TO-DO: Add the HTTP Status Code 403 (Forbidden) when the url is not in supported list
                }
                catch (UriFormatException uriFormatException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName,
                                         uriFormatException.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + uriFormatException.Message +
                                         uriFormatException.StackTrace);
                    returnStream = null;
                }
                catch (WebException webException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, webException.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + webException.Message +
                                         webException.StackTrace);
                    returnStream = null;
                }
                catch (Exception ex)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + ex.Message + ex.StackTrace);
                    returnStream = null;
                }
                if (WebOperationContext.Current != null)
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
                    HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                    WebOperationContext.Current.OutgoingResponse.Headers.Add(cacheHeader,
                                                                             string.Format(CultureInfo.InvariantCulture,
                                                                                           "max-age={0}, must-revalidate",
                                                                                           CachingDuration));
                    //Add one day caching
                }
            }
            return(returnStream);
        }
        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();
        }
Esempio n. 33
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);
        }
Esempio n. 34
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();
		}
Esempio n. 35
0
        public byte[] CreatePdf(PDFService.Settings settings)
        {
            if (settings == null) throw new ArgumentNullException("settings");
            if (!settings.Uris.Any()) throw new ArgumentException("No URIs provided to create PDF from");

            using (Doc pdf = new Doc())
            {
                pdf.HtmlOptions.Engine = EngineType.Gecko;

                pdf.HtmlOptions.Timeout = (int)settings.Timeout.TotalMilliseconds;
                pdf.HtmlOptions.RetryCount = settings.RetryCount;

                pdf.HtmlOptions.PageCacheClear();
                pdf.HtmlOptions.PageCacheEnabled = false;

                pdf.HtmlOptions.AddForms = settings.UseForms;
                pdf.HtmlOptions.AddLinks = settings.UseLinks;
                pdf.HtmlOptions.UseScript = settings.UseScript;

                pdf.Color.Red = 255;
                pdf.Color.Green = 255;
                pdf.Color.Blue = 255;

                pdf.Rect.Inset(10, 10);

                pdf.FillRect();

                // If selected, make the PDF in landscape format
                if (settings.UseLandscapeOrientation)
                {
                    pdf.Transform.Rotate(90, pdf.MediaBox.Left, pdf.MediaBox.Bottom);
                    pdf.Transform.Translate(pdf.MediaBox.Width, 0);
                    pdf.Rect.Width = pdf.MediaBox.Height;
                    pdf.Rect.Height = pdf.MediaBox.Width;
                }

                int imageId = 0;

                // For each URI provided, add the result to the output doc
                foreach (String uri in settings.Uris)
                {
                    if (imageId != 0)
                    {
                        pdf.Page = pdf.AddPage();
                    }

                    // Render the web page by uri and return the image id for chaining
                    imageId = pdf.AddImageUrl(uri, paged: true, width: 0, disableCache: false);

                    while (true)
                    {
                        // Stop when we reach a page which wasn't truncated, per the examples
                        if (!pdf.Chainable(imageId)) break;

                        // Add a page to the pdf and sets the page id
                        pdf.Page = pdf.AddPage();

                        // Add the previous image to the chain and set the image id
                        imageId = pdf.AddImageToChain(imageId);
                    }
                }

                // flatten the pages
                for (var ii = 1; ii <= pdf.PageCount; ii++)
                {
                    pdf.PageNumber = ii;
                    pdf.Flatten();
                }

                // Return the byte array representing the pdf
                return pdf.GetData();
            }
        }
        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();
        }
        protected void btnPrintBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {

            Doc theDoc = new Doc();
            //clear caching?
            theDoc.HtmlOptions.PageCacheEnabled = false;
            theDoc.HtmlOptions.UseNoCache = true;
            theDoc.HtmlOptions.PageCacheClear();
            theDoc.HtmlOptions.PageCachePurge();
            theDoc.HtmlOptions.UseResync = true;
            theDoc.Rect.String = "20 90 580 750";
            string hostURL = (HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://") + HttpContext.Current.Request.Url.Host.ToString();
            string callUrl = ResolveUrl("~/Controls/Credentials/PDF/CredentialListPdf.aspx");
            int theID;
            theID = theDoc.AddImageUrl(hostURL + callUrl);
            while (true)
            {

                if (!theDoc.Chainable(theID))
                    break;
                theDoc.Page = theDoc.AddPage();
                theID = theDoc.AddImageToChain(theID);
            }
            for (int i = 1; i <= theDoc.PageCount; i++)
            {
                theDoc.PageNumber = i;

                theDoc.Flatten();
            }
            theDoc = AddHeaderFooter(theDoc);
            byte[] pdf = theDoc.GetData();

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + "CredentialList" + ".pdf");
            Response.AddHeader("content-length", pdf.Length.ToString());
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(pdf);
            Response.End();
        }
        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;
        }
Esempio n. 39
0
        //public static  bool PageToPdfByteArray(string url, string path, Encoding encoe)
        //{
        //    byte[] pdfBuf;
        //    bool ret = false;
        //    try
        //    {
        //        GlobalConfig gc = new GlobalConfig();

        //        // set it up using fluent notation
        //        gc.SetMargins(new Margins(0, 0, 0, 0))
        //          .SetDocumentTitle("Test document")
        //          .SetPaperSize(PaperKind.A4);
        //        //... etc

        //        // create converter
        //        IPechkin pechkin = new SynchronizedPechkin(gc);

        //        // subscribe to events
        //        //pechkin.Begin += OnBegin;
        //        //pechkin.Error += OnError;
        //        //pechkin.Warning += OnWarning;
        //        //pechkin.PhaseChanged += OnPhase;
        //        //pechkin.ProgressChanged += OnProgress;
        //        //pechkin.Finished += OnFinished;

        //        // create document configuration object
        //        ObjectConfig oc = new ObjectConfig();

        //        // and set it up using fluent notation too
        //        oc.SetCreateExternalLinks(false)
        //        .SetFallbackEncoding(encoe)
        //        .SetLoadImages(true)
        //        .SetPageUri(url);
        //        //... etc

        //        // convert document
        //        pdfBuf = pechkin.Convert(oc);

        //        FileStream fs = new FileStream(path, FileMode.Create);
        //        fs.Write(pdfBuf, 0, pdfBuf.Length);
        //        fs.Close();
        //        ret = true;
        //    }
        //    catch (Exception ex)
        //    {

        //    }

        //    return ret;
        //}

        /// <summary>
        /// 根据页面url,按节点目录生成pdf和对应书签(空页面不生成)
        /// </summary>
        /// <param name="docList"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static bool MergePdf(List <PdfDoc> docList, string savePath)
        {
            if (docList.Count == 0)
            {
                return(false);
            }
            Doc doc = new Doc();

            doc.HtmlOptions.Timeout   = 30 * 1000;
            doc.HtmlOptions.UseScript = true;
            doc.Rect.Inset(36.0, 72.0);//Rect默认是文档整个页面大小, 这里的Inset表示将Rect左右留出36的空白,上下留出72的空白

            string emptyMarkPath = null;
            bool   emptyMarkExp  = false;

            try
            {
                foreach (PdfDoc pd in docList)
                {
                    if (pd.NodePid != 0) //0为根节点,没有页面
                    {
                        if (string.IsNullOrEmpty(pd.Url))
                        {
                            /**
                             * 有些目录可能没有页面内容,这里则先将目录的bookmark路径保存;
                             * **/
                            emptyMarkPath = GetPath(docList, pd).TrimEnd('\\');
                            emptyMarkExp  = pd.Expended;
                        }
                        else
                        {
                            doc.Page = doc.AddPage();
                            if (emptyMarkPath != null)
                            {
                                doc.AddBookmark(emptyMarkPath, emptyMarkExp); //让空目录指定到其第一个子页面
                                emptyMarkPath = null;                         //添加之后置空
                            }
                            doc.AddBookmark(GetPath(docList, pd).TrimEnd('\\'), pd.Expended);

                            int num = doc.AddImageUrl(pd.Url);
                            while (true)
                            {
                                //doc.FrameRect();//给内容区域添加黑色边框
                                if (!doc.Chainable(num))
                                {
                                    break;
                                }
                                doc.Page = doc.AddPage();
                                num      = doc.AddImageToChain(num);
                            }
                        }
                    }
                }
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Flatten();
                }
                if (!savePath.ToLower().EndsWith(".pdf"))
                {
                    savePath += ".pdf";
                }
                doc.Save(savePath);
            }
            catch (Exception ex)
            {
                LogError.ReportErrors(ex.Message);
                return(false);
            }
            finally
            {
                doc.Clear();
                doc.Dispose();
            }

            return(true);
        }
Esempio n. 40
0
        private int GetNumberOfPages(string url, string extension, int marginLeft, int marginTop)
        {
            this.margineLeft = marginLeft;
            this.margineTop  = marginTop;
            this.url         = url;
            int  PageCount = 0;
            bool isLogged  = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]);

            // This code line sets the license key to the Doc object
            XSettings.InstallRedistributionLicense(System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]);

            //Create a new Doc

            switch (extension)
            {
            //If the url is a pdf file
            case PDF:
                byte[] buffer   = new byte[4096];
                int    count    = 0;
                byte[] pdfBytes = null;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    WebRequest  webRequest  = WebRequest.Create(url);
                    WebResponse webResponse = webRequest.GetResponse();
                    Stream      stream      = webResponse.GetResponseStream();
                    do
                    {
                        count = stream.Read(buffer, 0, buffer.Length);
                        memoryStream.Write(buffer, 0, count);
                    } while (count != 0);

                    pdfBytes = memoryStream.ToArray();
                }
                using (Doc theDoc = new Doc())
                {
                    theDoc.HtmlOptions.UseScript        = true;
                    theDoc.HtmlOptions.UseActiveX       = true;
                    theDoc.HtmlOptions.UseVideo         = true;
                    theDoc.HtmlOptions.PageCacheEnabled = true;
                    theDoc.HtmlOptions.Timeout          = 120000;
                    theDoc.Rect.Inset(marginLeft, marginTop);
                    theDoc.Read(pdfBytes);
                    PageCount = theDoc.PageCount;
                }
                return(PageCount);

            //break;
            default:
                using (Doc htmlDoc = new Doc())
                {
                    //Start new thread to generate images when user call GetNumberOfPages method
                    htmlDoc.HtmlOptions.UseScript  = true;   // Enable javascript at the startup time
                    htmlDoc.HtmlOptions.UseActiveX = true;   // Enable SVG
                    htmlDoc.HtmlOptions.UseVideo   = true;   // Enable Video
                    htmlDoc.HtmlOptions.Timeout    = 120000;
                    // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html
                    htmlDoc.HtmlOptions.PageCacheEnabled = true;   // Enable ABCPDF .NET page cache
                    htmlDoc.Rect.Inset(marginLeft, marginTop);     // Insert the margin left and margin top
                    htmlDoc.Page = htmlDoc.AddPage();

                    int theID = htmlDoc.AddImageUrl(url.ToString());
                    // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                    while (true)
                    {
                        if (!htmlDoc.Chainable(theID))
                        {
                            break;
                        }
                        htmlDoc.Page = htmlDoc.AddPage();
                        htmlDoc.Rendering.DotsPerInch = constDotPerInches;    // set DPI = 150
                        htmlDoc.Rendering.SaveQuality = constSaveQuality;     // set Quality = 100
                        theID = htmlDoc.AddImageToChain(theID);
                    }
                    if (htmlDoc != null)
                    {
                        return(htmlDoc.PageCount);
                    }
                }
                break;
            }
            return(0);
        }
Esempio n. 41
0
        /// <summary>
        /// 按一级目录请求页面,二级和以后的目录全部不生成,书签只能定位到一级目录
        /// </summary>
        /// <param name="docList"></param>
        /// <param name="savePath"></param>
        /// <param name="customerName"></param>
        /// <param name="bookTaskUrl">为a标签包含的链接</param>
        /// <returns></returns>
        public static bool MergePdf4(List <PdfDoc> docList, string savePath, string customerName, string bookTaskUrl)
        {
            if (docList.Count == 0)
            {
                return(false);
            }
            Doc doc = new Doc();

            doc.HtmlOptions.Timeout          = 30 * 1000;
            doc.HtmlOptions.UseScript        = true;
            doc.HtmlOptions.UseNoCache       = true;
            doc.HtmlOptions.PageCacheEnabled = false;
            doc.HtmlOptions.PageCacheClear();
            doc.Rect.Inset(52.0, 100.0);

            try
            {
                Dictionary <int, string> titleDic = new Dictionary <int, string>();
                foreach (PdfDoc pd in docList)
                {
                    if (pd.NodePid == 0)//0为根节点,可能为封面,单独处理
                    {
                        continue;
                    }

                    doc.Page = doc.AddPage();
                    doc.AddBookmark(GetPath(docList, pd).TrimEnd('\\'), pd.Expended);
                    titleDic.Add(doc.PageCount, pd.Name);

                    if (pd.Url == null)
                    {
                        continue;
                    }
                    int num = doc.AddImageUrl(pd.Url);

                    while (true)
                    {
                        if (!doc.Chainable(num))
                        {
                            break;
                        }
                        doc.Page = doc.AddPage();
                        num      = doc.AddImageToChain(num);
                        titleDic.Add(doc.PageCount, pd.Name);
                    }
                }
                #region 添加页眉和页脚

                AddHeader(ref doc, titleDic, customerName, bookTaskUrl);
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    //压缩输出
                    doc.Flatten();
                }
                #endregion
                if (!savePath.ToLower().EndsWith(".pdf"))
                {
                    savePath += ".pdf";
                }
                doc.Save(savePath);
            }
            catch (Exception ex)
            {
                LogError.ReportErrors(ex.Message);
                return(false);
            }
            finally
            {
                doc.Clear();
                doc.Dispose();
            }

            return(true);
        }
Esempio n. 42
0
        public static ResponseVal ConvertHmlToPDF(string QuoteISN, string StaffISN)
        {
            Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------Begin----------");
            Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: QuoteISN: " + QuoteISN);
            Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: StaffISN: " + StaffISN);
            ResponseVal resVal = new ResponseVal();
            var         result = -1;

            //bool rsCheck = XSettings.InstallLicense("X/VKS08wmMtAun4hGNvFONzmS/QQY7hZ9Z2488LHIg8X5nu5Qx7dYsZhez00hWZRXd5Xim0uoXp3ifxwDtAusQ0lPTnPXR1401Y=");

            //bool rsCheck = XSettings.InstallLicense("XeJREBodo/8B4nxZb63WaYOgeuQZPdtypqn27rLhKmkRz3CDGnvCaco3Dn5c5nQFBw==");
            //bool rsCheck = XSettings.InstallLicense("XeJREBodo/8B7XFQaf2CPdzyKuccPdtypszj/8HiXH0n+nieP1jmdZIuAHpU7kIFBw==");
            //bool rsCheck = XSettings.InstallLicense("X/VKS0cNn5FipytaG9r2LN6gO9YNAb8f0JfhndPDLmJ14X+2ABmFVcU9cz81hwBrU4M7olk+wz9WgdFFKeN5mjkhfR3iZgJkr1Y=");

            bool rsCheck = XSettings.InstallLicense(Functions.GetConfig_CS("AbcPdfLicense"));

            if (!rsCheck)
            {
                resVal.Code = -1;
                resVal.Msg  = "Invalid Websupergoo license.";
                return(resVal);
            }

            var ds = Globals.DB.ExecuteQuery(string.Format("select MemberISN from Vw_SolarQuote where QuoteISN={0}", Functions.ConvertObjectToInt(QuoteISN)));

            if (Functions.IsEmpty(ds))
            {
                resVal.Code = -1;
                resVal.Data = null;
                resVal.Msg  = "QuoteISN is missing";
                Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: Msg: " + resVal.Msg);
                Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------");
                return(resVal);
            }

            var    row       = ds.Tables[0].Rows[0];
            var    MemberISN = row["MemberISN"].ToString();
            string url       = string.Format("{0}/Proposal.aspx?isn={1}&staffisn={2}",
                                             Functions.GetConfig_CS("AdminURL").TrimEnd('/'), QuoteISN, StaffISN);

            Globals.WriteLog("[ConvertHmlToPDF_CreateFile] -- url: " + url);

            string Temp          = Functions.GetConfig_CS("TemporaryDir");
            string outputPath    = HttpContext.Current.Server.MapPath("~/OutputFiles/Pdf");
            string sFileName     = "";
            string sFullPathTemp = "";

            #region Create PDF
            try
            {
                Doc pages = new Doc();
                try
                {
                    Doc doc = new Doc();
                    //doc.Rect.Inset(30, 10);
                    //doc.HtmlOptions.Engine = EngineType.MSHtml;
                    //doc.HtmlOptions.Engine = EngineType.Chrome;
                    //doc.HtmlOptions.Engine = EngineType.MSHtml;
                    //doc.SetInfo(0, "RenderDelay", "500");
                    //doc.SetInfo(0, "OneStageRender", 0);

                    doc.HtmlOptions.FontEmbed      = true;
                    doc.HtmlOptions.FontSubstitute = false;
                    doc.HtmlOptions.FontProtection = false;
                    doc.HtmlOptions.BrowserWidth   = 1200;

                    doc.HtmlOptions.PageCacheClear();
                    doc.HtmlOptions.UseScript = true;
                    //doc.HtmlOptions.OnLoadScript = "(function(){window.ABCpdf_go = false; setTimeout(function(){window.ABCpdf_go = true;}, 3000);})();";


                    // Render after 3 seconds
                    //doc.HtmlOptions.OnLoadScript = " (function(){"
                    //  + " window.external.ABCpdf_RenderWait();"
                    //  + " setTimeout(function(){ "
                    //  + " window.external.ABCpdf_RenderComplete(); }, 5000);"
                    //  + "})();";
                    //doc.SetInfo(0, "RenderDelay", "5000");
                    //doc.SetInfo(0, "OneStageRender", 0);

                    //Render after 3 seconds
                    //doc.HtmlOptions.OnLoadScript = "(function(){"
                    //  + " window.ABCpdf_go = false;"
                    //  + " setTimeout(function(){ window.ABCpdf_go = true; }, 10000);"
                    //  + "})();";

                    doc.Page = doc.AddPage();
                    int theID;

                    theID = doc.AddImageUrl(url);

                    while (true)
                    {
                        doc.FrameRect(); // add a black border
                        if (!doc.Chainable(theID))
                        {
                            break;
                        }
                        doc.Page = doc.AddPage();
                        theID    = doc.AddImageToChain(theID);

                        System.Threading.Thread.Sleep(500);
                    }

                    //doc.Rect.String = "100 50 500 150";

                    //for (int i = 1; i <= doc.PageCount; i++)
                    //{
                    //    doc.PageNumber = i;
                    //    doc.AddText("Page " + i.ToString());
                    //    //doc.FrameRect();
                    //}

                    pages.Append(doc);
                }
                catch (Exception ex2)
                {
                    resVal.Code = -1;
                    resVal.Data = null;
                    resVal.Msg  = ex2.Message;
                    Globals.WriteLog("[ConvertHmlToPDF_CreateFile] - Exception: " + ex2.Message);
                    Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------");
                    return(resVal);
                }

                if (!System.IO.File.Exists(Temp))
                {
                    System.IO.Directory.CreateDirectory(Temp);
                }

                Globals.WriteLog("[ConvertHmlToPDF_CreateFile] Temp: " + Temp);

                sFileName     = "Proposal_" + DateTime.Now.Ticks.ToString() + ".pdf";
                sFullPathTemp = Path.Combine(Temp, sFileName);

                pages.Save(sFullPathTemp);
                pages.Clear();

                string sDocName = "Proposal_" + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;

                result = (int)Globals.DB.ExecuteStoredProc("xp_debtext_documenttask_insupd",
                                                           new string[] { "DocumentISN", "docFileName", "docName", "docType", "docPublic", "MemberISN" },
                                                           new object[] { 0, sFileName, sDocName, "Proposal", 1, MemberISN });

                var sPathFileDoc = Path.Combine(Functions.GetConfig_CS("FilesDir"), GetDocumentsPath(result, null));

                if (!System.IO.File.Exists(sPathFileDoc))
                {
                    System.IO.Directory.CreateDirectory(sPathFileDoc);
                }

                var sFileSave = Path.Combine(sPathFileDoc, sFileName);
                File.Copy(sFullPathTemp, sFileSave);
                //File.Delete(sFullPathTemp);
                resVal.Code = 1;
                resVal.Data = result;
                resVal.Msg  = "Success";

                Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sFullPathTemp: " + sFullPathTemp);
                Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sPathFileDoc: " + sFileSave);
                Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sFileName: " + sFileName);
                Globals.WriteLog("[ConvertHmlToPDF_CreateFile] DocumentISN: " + result);
            }
            catch (Exception ex)
            {
                resVal.Code = -1;
                resVal.Data = null;
                resVal.Msg  = ex.Message;
                Globals.WriteLog("[ConvertHmlToPDF_CreateFile] -- Exception: " + ex.Message);
            }
            Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------");
            #endregion

            #region old
            // string fileName = DateTime.Now.Ticks + ".pdf";
            // string pathFileName = Path.Combine(Functions.GetConfig_CS("TemporaryDir"), fileName);
            // string ContentHtml = ReadFromFile(pathFileHtml);

            // //StringBuilder sb = new StringBuilder();
            // //sb.Append(ContentHtml);

            // //var css = ContentHtml.Substring(ContentHtml.IndexOf("<style>") + 7, ContentHtml.IndexOf("</style>") - 7 - ContentHtml.IndexOf("<style>"));
            //// var js = ContentHtml.Substring(ContentHtml.IndexOf("<script>") + 8, ContentHtml.IndexOf("</script>") - 8 - ContentHtml.IndexOf("<script>"));

            // StringReader sr = new StringReader(ContentHtml);

            // //StringWriter sw = new StringWriter();

            // //HtmlTextWriter hw = new HtmlTextWriter(sw);
            // //hw.Write(ContentHtml);
            // Document pdfDoc = new Document(PageSize.A4);
            // //HTMLWorker htmlparser = new HTMLWorker(pdfDoc);


            // using (MemoryStream memoryStream = new MemoryStream())
            // {
            //     PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            //     pdfDoc.Open();

            //     //htmlparser.Parse(new StringReader(sw.ToString()));
            //     ////HTMLWorker.ParseToList(sr, new StyleSheet());
            //     //pdfDoc.Close();

            //     //StyleSheet ss = new StyleSheet();

            //     //ArrayList list = HTMLWorker.ParseToList(new StringReader(ContentHtml), ss);
            //     //foreach (IElement e in list)
            //     //{
            //     //    pdfDoc.Add(e);
            //     //
            //     //using (TextReader sReader = new StringReader(ContentHtml.ToString()))
            //     //{
            //     //    ArrayList list = HTMLWorker.ParseToList(sReader, new StyleSheet());
            //     //    foreach (IElement elm in list)
            //     //    {
            //     //        pdfDoc.Add(elm);
            //     //    }
            //     //}
            //     //pdfDoc.HtmlStyleClass = ContentHtml;
            //     //pdfDoc.JavaScript_onLoad = ContentHtml;
            //     //htmlparser.Parse(sr);
            //     // step 5
            //     //Image img = Image.GetInstance(ContentHtml);
            //     //pdfDoc.Add(img);
            //     //writer.AddJavaScript(ContentHtml);
            //     iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);

            //     //using (var srHtml = new StringReader(ContentHtml))
            //     //{

            //     //    //Parse the HTML
            //     //    iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, srHtml);
            //     //}

            //     //using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css)))
            //     //{
            //     //    using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(ContentHtml)))
            //     //    {

            //     //        Parse the HTML
            //     //        iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, msHtml, msCss);
            //     //    }
            //     //}

            //     pdfDoc.Close();

            //     byte[] bytes = memoryStream.ToArray();

            //     //BinaryFormatter bf = new BinaryFormatter();
            //     //MemoryStream ms = new MemoryStream();
            //     //bf.Serialize(ms, ContentHtml);
            //     //bytes = ms.ToArray();

            //     pathFileName = pathFileName + ".pdf";
            //     System.IO.File.WriteAllBytes(pathFileName, bytes);
            //     memoryStream.Close();
            //     File.Copy(Path.Combine(Functions.GetConfig_CS("TemporaryDir"), fileName + ".pdf"), Path.Combine(Functions.GetConfig_CS("FilesConvertPdf"), fileName + ".pdf"), true);
            //     resVal.Code = 1;
            //     resVal.Data = pathFileName;
            //     resVal.Msg = "Success";
            // }
            #endregion

            return(resVal);
        }
 private void CreatePDFFetched(EngineType engine)
 {
     var connectionString = ConfigurationManager.ConnectionStrings["LicenseKey"].ConnectionString;
     XSettings.InstallLicense(connectionString);
     var theDoc = new Doc();
     theDoc.HtmlOptions.Engine = engine;
     theDoc.HtmlOptions.UseScript = false;
     theDoc.HtmlOptions.BrowserWidth = 800;
     theDoc.HtmlOptions.ForGecko.UseScript = false;
     theDoc.Rendering.DotsPerInch = 300;
     theDoc.HtmlOptions.ForGecko.InitialWidth = 800;
     theDoc.Rect.Inset(18, 18);
     theDoc.Page = theDoc.AddPage();
     int theID = theDoc.AddImageUrl("http://woot.com/", true, 800, true);
     while (true)
     {
         theDoc.FrameRect(); // add a black border
         if (!theDoc.Chainable(theID))
             break;
         theDoc.Page = theDoc.AddPage();
         theID = theDoc.AddImageToChain(theID);
     }
     for (int i = 1; i <= theDoc.PageCount; i++)
     {
         theDoc.PageNumber = i;
         theDoc.Flatten();
     }
     Response.Buffer = false;
     Response.AddHeader("Content-Disposition", "inline; filename=\"rept.pdf\"");
     Response.ContentType = "application/pdf";
     theDoc.Save(Response.OutputStream);
     Response.Flush();
 }
Esempio n. 44
0
        public void GeneratePdfForHaf(string pageurl, string fileSavePath, string corporateSurveyPdf = "", string basicBiometricFile = "", string focAttestationFile = "", string corporateCheckListPdf = "", string annualComprehensiveExamPdf = "",
                                      string memberInformationProfilePdf = "")
        {
            var finalReport = new Doc();

            try
            {
                finalReport.Rect.Inset(40, 70);
                //pdfDoc.Rect.
                finalReport.MediaBox.String = PaperSize;
                finalReport.Rect.String     = finalReport.MediaBox.String;
                finalReport.Page            = finalReport.AddPage();
                finalReport.HtmlOptions.PageCachePurge();
                finalReport.HtmlOptions.Timeout = 90000;

                if (AllowLoadingJavascriptbeforePdfGenerate)
                {
                    finalReport.HtmlOptions.UseScript = true;
                }

                int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true);

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

                for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++)
                {
                    finalReport.PageNumber = pageNumber;
                    //Flatten page
                    finalReport.Flatten();
                }

                if (!string.IsNullOrEmpty(basicBiometricFile))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(basicBiometricFile);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(corporateSurveyPdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(corporateSurveyPdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(focAttestationFile))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(focAttestationFile);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }
                if (!string.IsNullOrEmpty(corporateCheckListPdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(corporateCheckListPdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }
                if (!string.IsNullOrEmpty(annualComprehensiveExamPdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(annualComprehensiveExamPdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }
                if (!string.IsNullOrEmpty(memberInformationProfilePdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(memberInformationProfilePdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                finalReport.Save(fileSavePath);
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                finalReport.Clear();
                finalReport.Dispose();
            }
        }
        private int GetNumberOfPages(string url, string extension, int marginLeft, int marginTop)
        {
            this.margineLeft = marginLeft;
            this.margineTop = marginTop;
            this.url = url;
            int PageCount = 0;
            bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]);
            // This code line sets the license key to the Doc object
            XSettings.InstallRedistributionLicense(System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]);

            //Create a new Doc

            switch (extension)
            {
                //If the url is a pdf file
                case PDF:
                    byte[] buffer = new byte[4096];
                    int count = 0;
                    byte[] pdfBytes = null;

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        WebRequest webRequest = WebRequest.Create(url);
                        WebResponse webResponse = webRequest.GetResponse();
                        Stream stream = webResponse.GetResponseStream();
                        do
                        {
                            count = stream.Read(buffer, 0, buffer.Length);
                            memoryStream.Write(buffer, 0, count);

                        } while (count != 0);

                        pdfBytes = memoryStream.ToArray();

                    }
                    using (Doc theDoc = new Doc())
                    {
                        theDoc.HtmlOptions.UseScript = true;
                        theDoc.HtmlOptions.UseActiveX = true;
                        theDoc.HtmlOptions.UseVideo = true;
                        theDoc.HtmlOptions.PageCacheEnabled = true;
                        theDoc.HtmlOptions.Timeout = 120000;
                        theDoc.Rect.Inset(marginLeft, marginTop);
                        theDoc.Read(pdfBytes);
                        PageCount = theDoc.PageCount;
                    }
                    return PageCount;
                //break;
                default:
                    using (Doc htmlDoc = new Doc())
                    {
                        //Start new thread to generate images when user call GetNumberOfPages method
                        htmlDoc.HtmlOptions.UseScript = true; // Enable javascript at the startup time
                        htmlDoc.HtmlOptions.UseActiveX = true; // Enable SVG
                        htmlDoc.HtmlOptions.UseVideo = true; // Enable Video
                        htmlDoc.HtmlOptions.Timeout = 120000;
                        // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html
                        htmlDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache
                        htmlDoc.Rect.Inset(marginLeft, marginTop); // Insert the margin left and margin top
                        htmlDoc.Page = htmlDoc.AddPage();

                        int theID = htmlDoc.AddImageUrl(url.ToString());
                        // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                        while (true)
                        {
                            if (!htmlDoc.Chainable(theID))
                                break;
                            htmlDoc.Page = htmlDoc.AddPage();
                            htmlDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150
                            htmlDoc.Rendering.SaveQuality = constSaveQuality; // set Quality = 100
                            theID = htmlDoc.AddImageToChain(theID);
                        }
                        if (htmlDoc != null)
                            return htmlDoc.PageCount;
                    }
                    break;
            }
            return 0;
        }
Esempio n. 46
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;
            }
        }
Esempio n. 47
0
        public String gerarRelatorioPDF(string cdaEmpCadastro, string cpfCnpj, string cdaQuestionarioEmpresa, string protocolo, string estado, string categoria, Boolean comentarios, Int32 programaId, Int32 turmaId, Int32 avaliador, Int32 intro, Boolean EnviaEmail, Page page)
        {
            if (avaliador == 0)
            {
                new BllQuestionarioEmpresa().AlterarSomenteFlagLeitura(StringUtils.ToInt(cdaQuestionarioEmpresa), true);
            }

            Session.Timeout      = 13000;
            Server.ScriptTimeout = 13000;

            string caminhoFisicoRelatorios = ConfigurationManager.AppSettings["caminhoFisicoRelatorios"];
            string caminhoPaginaRelatorio  = ConfigurationManager.AppSettings["caminhoPaginaRelatorio"];

            try
            {
                string[] files = Directory.GetFiles(caminhoFisicoRelatorios);
                foreach (string file in files)
                {
                    if (!File.GetCreationTime(file).ToShortDateString().Equals(DateTime.Now.ToShortDateString()))
                    {
                        File.Delete(file);
                    }
                }
            }
            catch { }
            string c = "";

            try
            {
                int chave = 0;
                if (comentarios)
                {
                    chave = 1;
                }

                //if (programaId == 3)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2008"];
                //}
                //else if (programaId == 4)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2009"];
                //}
                //else if (programaId == 7)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorioAutoavaliacao"];
                //}

                Doc theDoc = new Doc();
                theDoc.SetInfo(0, "License", "bc8b5c07da69df2b6c476901f513aa8b89ff6d8ce56a16797802be20da7348078ab9ae58bd6c483b");
                theDoc.HtmlOptions.Timeout = 30000000;


                String link = this.getDominio(page) + caminhoPaginaRelatorio + "?CDA_EMP_CADASTRO=" + cdaEmpCadastro + "&TX_CPF_CNPJ=" + cpfCnpj + "&Chave=" + chave + "&Avaliador=" + avaliador + "&Intro=" + intro + "&CEA_QUESTIONARIO_EMPRESA=" + cdaQuestionarioEmpresa + "&Protocolo=" + protocolo + "&turmaId=" + turmaId + "&programaId=" + programaId;

                if (estado != null)
                {
                    link = link + "&naoMostraComentarioJuiz=1";
                }
                else if (page.Request["naoMostraComentarioJuiz"] != null && page.Request["naoMostraComentarioJuiz"].Equals("1"))
                {
                    link = link + "&naoMostraComentarioJuiz=1";
                }
                int theID = theDoc.AddImageUrl(link, true, 1000, true);
                while (true)
                {
                    theDoc.FrameRect();
                    if (!theDoc.Chainable(theID))
                    {
                        break;
                    }
                    theDoc.Page = theDoc.AddPage();
                    theID       = theDoc.AddImageToChain(theID);
                }

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

                String ArquivoNome = protocolo + "_" + DateTime.Now.Ticks + ".pdf";
                String CaminhoPDF  = caminhoFisicoRelatorios + ArquivoNome;

                CaminhoPDF = Server.MapPath(CaminhoPDF);

                theDoc.Save(CaminhoPDF);
                theDoc.HtmlOptions.PageCacheClear();
                theDoc.Clear();

                theDoc.Delete(theID);
                theDoc.Dispose();

                theDoc = null;
                GC.Collect();


                Thread.Sleep(5000);

                if (EnviaEmail)
                {
                    //WebUtils.EnviaEmail(Request.QueryString["EmailContato"], "Relatório de AutoAvaliação", new System.Text.StringBuilder(), CaminhoPDF);
                    return(CaminhoPDF);
                    //ClientScript.RegisterClientScriptBlock(Page.GetType(), "closeWindow", "window.close();", true);
                }
                else
                {
                    //Response.Redirect(getDominio(this.Page) + "/Relatorios/" + ArquivoNome);
                    //return null;
                    return("/Relatorios/" + ArquivoNome);
                }
            }
            catch (Exception ex)
            {
                //Response.Write(ex.ToString());
                throw ex;
            }
            return(null);
        }
Esempio n. 48
0
        public byte[] Convert(string link, string width, string height)
        {
            try
            {
                var theDoc = new Doc();

                theDoc.SetInfo(0, "License", "141-819-141-276-8435-093");
                double pageWidth = System.Convert.ToDouble(width.ToUpper().Replace("PX", ""));
                double pageHeight = System.Convert.ToDouble(height.ToUpper().Replace("PX", "")) * 1.762;
                if (pageHeight>=14400)
                {
                    pageHeight = 14400;
                }
                theDoc.MediaBox.Width = pageWidth;
                theDoc.MediaBox.Height = pageHeight;
                theDoc.Rect.Width = pageWidth;
                theDoc.Rect.Height = pageHeight;
                theDoc.Rect.Inset(5, 5);
                theDoc.HtmlOptions.AddLinks = true;

                theDoc.Page = theDoc.AddPage();
                var theId = theDoc.AddImageUrl(link, false, 0, true);

                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;
            }
        }
Esempio n. 49
0
    public static bool createPdf(long jid,string journo,string email)
    {
        string contents = string.Empty;

        MemoryStream ms = new MemoryStream();

        try {
            int id;
            Doc doc = new Doc();

            doc.MediaBox.String = "A4";
            doc.HtmlOptions.BrowserWidth = 980;
            doc.HtmlOptions.FontEmbed = true;
            doc.HtmlOptions.FontSubstitute = false;
            doc.HtmlOptions.FontProtection = false;
            doc.HtmlOptions.ImageQuality = 33;
            Random rnd = new Random();
            id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/jour_pdf.aspx?id=" + jid.ToString() + "&uid="+ email +"&rnd=" + rnd.Next(50000));

            while (true) {
                //doc.FrameRect();
                if (!doc.Chainable(id)) {
                    break;
                }
                doc.Page = doc.AddPage();
                id = doc.AddImageToChain(id);
            }

            doc.Rect.String = "10 780 595 840";
            doc.HPos = 0.5;
            doc.VPos = 0.0;
            doc.Color.String = "0 255 0";
            doc.FontSize = 36;
            for (int i = 1; i <= doc.PageCount; i++) {
                doc.PageNumber = i;
                id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/header.aspx?id=" + jid.ToString() + "&rnd=" + rnd.Next(50000));
            }

            doc.Rect.String = "10 0 585 100";
            doc.HPos = 0.5;
            doc.VPos = 1.0;
            //doc.FontSize = 36;
            //for (int i = 1; i <= doc.PageCount; i++) {
                doc.PageNumber = 1;
                id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/footer.aspx?rnd=" + rnd.Next(50000));
                //doc.AddText("Page " + i.ToString() + " of " + doc.PageCount.ToString());
                //doc.FrameRect();
            //}

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

            //doc.AddImageHtml(contents);
            //doc.Save(Server.MapPath("htmlimport.pdf"));
            doc.Save(ms);
            //doc.SaveOptions.
            doc.Clear();

            bool mail = Common.PdfMail(ms, email);
            if (mail) {
                return AmazonHandler.PutPdfJour(ms, journo);
            }
            return false;

            //}
        } catch (Exception ex) {
            return false;
        }
    }
Esempio n. 50
0
        public static string ConvertHtmlToPDF(string filePathHTML)
        {
            WriteLog("[ConvertHmlToPDF_CreateFile]: ----------Begin----------");
            WriteLog("[ConvertHmlToPDF_CreateFile] filePathHTML: " + filePathHTML);
            string result  = string.Empty;
            bool   rsCheck = XSettings.InstallLicense("X/VKS08wmMtAun4hGNvFONzmS/QQY7hZ9Z2488LHIg8X5nu5Qx7dYsZhez00hWZRXd5Xim0uoXp3ifxwDtAusQ0lPTnPXR1401Y=");

            if (!rsCheck)
            {
                result = "Invalid Websupergoo license.";
                WriteLog("[ConvertHmlToPDF_CreateFile] result:  " + result);
                return(null);
            }
            string FilesDir = Functions.GetAppConfigByKey("FileDir");

            if (!System.IO.File.Exists(FilesDir))
            {
                System.IO.Directory.CreateDirectory(FilesDir);
            }

            string fileName = "File_Convert_PDF" + DateTime.Now.Ticks.ToString() + ".pdf";

            string fullPath = Path.Combine(FilesDir, fileName);

            WriteLog("[ConvertHmlToPDF_CreateFile] FilesDir: " + FilesDir);
            WriteLog("[ConvertHmlToPDF_CreateFile] fileName: " + fileName);
            WriteLog("[ConvertHmlToPDF_CreateFile] fullPath: " + fullPath);

            #region Create PDF
            try
            {
                Doc pages = new Doc();
                try
                {
                    Doc doc = new Doc();
                    //doc.Rect.Inset(30, 10);
                    //doc.HtmlOptions.Engine = EngineType.MSHtml;
                    //doc.HtmlOptions.Engine = EngineType.Chrome;

                    doc.HtmlOptions.FontEmbed      = true;
                    doc.HtmlOptions.FontSubstitute = false;
                    doc.HtmlOptions.FontProtection = false;
                    doc.HtmlOptions.BrowserWidth   = 1200;

                    doc.HtmlOptions.PageCacheClear();
                    doc.HtmlOptions.UseScript = true;
                    //doc.HtmlOptions.OnLoadScript = "(function(){window.ABCpdf_go = false; setTimeout(function(){window.ABCpdf_go = true;}, 3000);})();";

                    // Render after 3 seconds
                    //doc.HtmlOptions.OnLoadScript = " (function(){"
                    //  + " window.external.ABCpdf_RenderWait();"
                    //  + " setTimeout(function(){ "
                    //  + " window.external.ABCpdf_RenderComplete(); }, 10000);"
                    //  + "})();";
                    //doc.SetInfo(0, "RenderDelay", "45000");
                    //doc.SetInfo(0, "OneStageRender", 0);

                    //Render after 3 seconds
                    //doc.HtmlOptions.OnLoadScript = "(function(){"
                    //  + " window.ABCpdf_go = false;"
                    //  + " setTimeout(function(){ window.ABCpdf_go = true; }, 10000);"
                    //  + "})();";

                    doc.Page = doc.AddPage();
                    int theID;

                    theID = doc.AddImageUrl(filePathHTML);

                    while (true)
                    {
                        doc.FrameRect(); // add a black border
                        if (!doc.Chainable(theID))
                        {
                            break;
                        }
                        doc.Page = doc.AddPage();
                        theID    = doc.AddImageToChain(theID);

                        System.Threading.Thread.Sleep(500);
                    }

                    //doc.Rect.String = "100 50 500 150";

                    //for (int i = 1; i <= doc.PageCount; i++)
                    //{
                    //    doc.PageNumber = i;
                    //    doc.AddText("Page " + i.ToString());
                    //    //doc.FrameRect();
                    //}

                    pages.Append(doc);
                }
                catch (Exception ex2)
                {
                    result = ex2.Message;
                    WriteLog("[ConvertHmlToPDF_CreateFile] - Exception: " + result);
                    return(null);
                }

                pages.Save(fullPath);
                pages.Clear();
                result = fullPath;

                WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------");
                return(result);
            }
            catch (Exception ex)
            {
                result = ex.Message;
                WriteLog("[ConvertHmlToPDF_CreateFile] -- Exception: " + result);
                return(null);
            }
            #endregion
        }