Пример #1
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();
        }
Пример #2
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);
        }
    }
Пример #3
0
    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;
        }
    }
        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();

        }
Пример #5
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;
            }
        }
        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();
        }
Пример #7
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;
            }
        }
Пример #8
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;
            }
        }
Пример #9
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);
        }
Пример #10
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;
        }
        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 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;
        }
Пример #13
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();
            }
        }
Пример #14
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);
        }
        /// <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;
        }
Пример #16
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);
            }
        //}
    }
        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;
        }
Пример #18
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;
        }
 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();
 }
Пример #20
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;
        }
    }
Пример #21
0
        /// <summary>
        /// When a Level A User clicks finish several things occur:
        /// <list type="bullet">
        ///	<item>The status of the cart is changed to submitted.</item>
        ///	<item>The name of the cart is changed so that new carts can be created with the cart's name.</item>
        ///	<item>An email is sent out informing the user that the cart was submitted.</item>
        /// </list>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitCart_Click(object sender, EventArgs e)
        {
            //This only occurs for Level A USERS

            //Generate Confirmation Number
            string webConfirmationNumber = NWTD.Orders.Cart.GenerateOrderNumber(this.CheckoutCart);

            //Set the Confirmation Number on the cart
            this.CheckoutCart["WebConfirmation"] = webConfirmationNumber;
            //Save Confirmation # to cart so it can be used by CheckoutSummaryPrint for PDF (Heath Gardner 08/19/13)
            //NOTE: Must do save here before changing status and cart name. Otherwise cart won't be found for CheckoutSummaryPrint (hg)
            this.SaveChanges();

            //Set cart status to SUBMITTED
            this.CheckoutCart.Status = NWTD.Orders.Cart.CART_STATUS.SUBMITTED.ToString();
            //change the name of the cart so future carts with the same name can be created
            this.CheckoutCart.Name = this.CheckoutCart.Name + "_" + this.CheckoutCart.Id;

            //The following two lines have been moved to above, so we can not only generate the number but SAVE it as well (Heath Gardner 08/19/13)
            //string webConfirmationNumber = NWTD.Orders.Cart.GenerateOrderNumber(this.CheckoutCart); //generate a confirmation numbmer
            //this.CheckoutCart["WebConfirmation"] = webConfirmationNumber; //set the confirmation number on the cart

            //Create the Order Summary pdf via abcPDF
            using (var doc = new Doc())
            {
                doc.HtmlOptions.Media = MediaType.Print;

                //Heath Gardner Replaced below "AddImageUrl" code to work with multiple page documents per WebSuperGoo's documentation
                //doc.AddImageUrl(string.Format("{0}/checkout/ordersummaryprint.aspx?cart={1}&uid={2}&IsLevelA={3}",
                //                              GetHost(), Request["cart"], ProfileContext.Current.UserId,
                //                              NWTD.Profile.CurrentUserLevel.Equals(NWTD.UserLevel.A)));

                ////////Beginning of Added functionality to "inset", create mulitple page PDFs, and to "flatten" the PDF (Heath Gardner 03/22/13)
                int docID;

                //Inset doc object edges so PDF Margins are acceptable (HG 03/22/13)
                doc.Rect.Inset(30, 30);

                //Create the first page and save the docID (HG 03/22/13)
                //Added 'true' to end of AddImageUrl call to "disable cache". Fixes duplicate PDF issue (Heath Gardner 03/22/13)
                docID = doc.AddImageUrl(string.Format("{0}/checkout/ordersummaryprint.aspx?cart={1}&uid={2}&IsLevelA={3}",
                                                      GetHost(), Request["cart"], ProfileContext.Current.UserId,
                                                      NWTD.Profile.CurrentUserLevel.Equals(NWTD.UserLevel.A)), true, 0, true);

                //Chain the subsequent pages together. Stop when we reach a page that is not truncated (HG 03/22/13)
                while (true)
                {
                    doc.FrameRect();
                    if (!doc.Chainable(docID))
                    {
                        break;
                    }
                    doc.Page = doc.AddPage();
                    docID    = doc.AddImageToChain(docID);
                }

                //Flatten each page of the PDF document per abcPDF's best practices (HG 03/22/13)
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Flatten();
                }
                ////////End of of Added functionality to "inset", create mulitple page PDFs, and to "flatten" the PDF (Heath Gardner 03/22/13)

                doc.Save(Server.MapPath(string.Format("~/Orders/{0}.pdf", webConfirmationNumber)));
                doc.Clear();
            }
            this.SaveChanges();    //save the cart


            //send the email
            try {
                //we won't be converting to a PurchaseOrder anymore. Keep it as a cart, change the cart's status.
                //this.CheckoutCart.OrderNumberMethod = new Mediachase.Commerce.Orders.Cart.CreateOrderNumber(NWTD.Orders.Cart.GenerateOrderNumber);
                //this._puchaseOrder = this.CheckoutCart.SaveAsPurchaseOrder();
                try {
                    this.SendConfirmationEmail();
                }
                catch (Exception ex) {
                    this.OrderMessage.Text += string.Format("Your order was submitted, however there was a problem sending your confirmation email: {0}", ex.Message);
                }
            }
            catch (Exception ex) {
                this.OrderMessage.Text += string.Format("There was an error creating a purchase order: {0}", ex.Message);
            }

            //indicate that the order is complete
            this.ShowOrderComplete();
            //Response.Redirect(NavigationManager.GetUrl("OrderThanks"));
        }