示例#1
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;
        }
    }
示例#2
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);
        }
示例#3
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();
        }
示例#4
0
        public string ExtractPdfPagesFromEnd(string sourcePath, string destinationPath, int numberOfPages)
        {
            var sourceDoc = new Doc();

            sourceDoc.Read(sourcePath);
            var sourceCount = sourceDoc.PageCount;

            if (numberOfPages > sourceCount)
            {
                throw new IndexOutOfRangeException(string.Format("Unable to extract pages from {0}.\nNumber of pages in source document less than required number of pages : {1}.", sourcePath, numberOfPages));
            }

            var destinationDoc = new Doc();

            destinationDoc.MediaBox.String = sourceDoc.MediaBox.String;
            destinationDoc.Rect.String     = destinationDoc.MediaBox.String;

            for (var i = sourceCount - numberOfPages + 1; i <= sourceCount; i++)
            {
                destinationDoc.Page = destinationDoc.AddPage();
                destinationDoc.AddImageDoc(sourceDoc, i, null);
                destinationDoc.FrameRect();
            }

            destinationDoc.Save(destinationPath);
            return(destinationPath);
        }
示例#5
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();
        }
    }
示例#6
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);
        }
        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);
        }
示例#8
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;
            }
        }
示例#9
0
        private void createButton1_Click(object sender, EventArgs e)
        {
            Doc          doc    = new Doc();
            Properties   props  = Properties.FromDoc(doc, true);
            List <Group> groups = new List <Group>();

            for (int i = 1; i < 4; i++)
            {
                groups.Add(props.AddGroup("Layer " + i.ToString(), null));
            }
            doc.FontSize = 36;
            doc.Rect.Inset(20, 20);
            for (int i = 0; i < 1; i++)
            {
                doc.Page = doc.AddPage();
                Page   page   = (Page)doc.ObjectSoup[doc.Page];
                Writer writer = new Writer(props, page);
                foreach (Group group in groups)
                {
                    OptionalContent.Layer layer = writer.AddGroup(group);
                    writer.StartLayer(layer);
                    doc.AddText(group.EntryName.Text + "\r\n");
                    writer.EndLayer();
                    doc.AddText("Always Visible\r\n");
                    writer.StartLayer(layer);
                    doc.AddText(group.EntryName.Text + "\r\n\r\n");
                    writer.EndLayer();
                }
                doc.Flatten();
            }
            LoadPDF(doc);
        }
示例#10
0
        public void ExtractPdfPages(string sourcePath, string destinationPath, int startPageNumber, int endPageNumber)
        {
            var sourceDoc = new Doc();

            sourceDoc.Read(sourcePath);
            var sourceCount = sourceDoc.PageCount;

            if (endPageNumber > sourceCount)
            {
                throw new IndexOutOfRangeException(string.Format("Unable to extract pages from {0}.\nNumber of pages in source document less than end page number.", sourcePath));
            }

            var destinationDoc = new Doc();

            destinationDoc.MediaBox.String = sourceDoc.MediaBox.String;
            destinationDoc.Rect.String     = destinationDoc.MediaBox.String;
            destinationDoc.Rect.Magnify(0.5, 0.5);
            destinationDoc.Rect.Inset(10, 10);

            for (int i = startPageNumber; i <= endPageNumber; i++)
            {
                destinationDoc.Page = destinationDoc.AddPage();
                destinationDoc.AddImageDoc(sourceDoc, i, null);
                destinationDoc.FrameRect();
            }
            destinationDoc.Save(destinationPath);
        }
        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);
        }
示例#12
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;
            }
        }
 public void Processing(object sender, ProcessingObjectEventArgs e)
 {
     if (e.Info.SourceType == ProcessingSourceType.PageContent)
     {
         _doc.Page      = _doc.AddPage();
         e.Info.Handled = true;
         _pagesAdded++;
     }
 }
示例#14
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();
        }
示例#15
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);
        }
    }
示例#16
0
        public int MergeDocuments(List <string> documentsToMergeList, List <string> documentsToCreateAndMergeList, string outputLocation, PdfPageSizeEnum pageSizeEnum)
        {
            try
            {
                using (Doc doc1 = new Doc())
                {
                    //set the page size of the entire document
                    doc1.MediaBox.String = pageSizeEnum.ToString();

                    //Merge existing documents
                    foreach (var documentToMerge in documentsToMergeList)
                    {
                        Doc doc2 = new Doc();

                        doc2.Read(documentToMerge);

                        //add each page of the plan to the doc2. It will add it as A4 size
                        for (int i = 1; i <= doc2.PageCount; i++)
                        {
                            doc1.Page = doc1.AddPage();
                            doc1.AddImageDoc(doc2, i, null);
                            doc1.FrameRect();
                        }

                        doc2.Dispose();
                    }

                    //Create New documents and Merge
                    foreach (var documentToCreateAndMerge in documentsToCreateAndMergeList)
                    {
                        using (Doc doc2 = new Doc())
                        {
                            doc2.FontSize = 40;
                            doc2.AddText(documentToCreateAndMerge);
                            doc1.Append(doc2);
                        }
                    }

                    doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString());
                    doc1.Encryption.CanEdit      = false;
                    doc1.Encryption.CanChange    = false;
                    doc1.Encryption.CanFillForms = false;
                    doc1.Save(outputLocation);
                    return(doc1.PageCount);
                }
            }
            catch (Exception e)
            {
                var documents = string.Join(", ", (from l in documentsToMergeList select l));
                //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e);
                //Throw the stack trace with it.
                throw;
            }
        }
示例#17
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();
                });
            });
        }
示例#18
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);
        }
示例#19
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);
        }
    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;
        }
    }
示例#21
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);
            }
        }
示例#22
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;
            }
        }
        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();

        }
示例#24
0
        private void createButton2_Click(object sender, EventArgs e)
        {
            Doc          doc    = new Doc();
            Properties   props  = Properties.FromDoc(doc, true);
            Group        parent = null;
            List <Group> groups = new List <Group>();

            // The Optional Content Group parent determines the nesting in the UI.
            // The presentation of the nesting is separate from the actual nesting
            // of visibility. In general you will want to ensure the two correspond
            // as in the code here.
            for (int i = 1; i <= 10; i++)
            {
                Group group = props.AddGroup("Layer " + i.ToString(), parent);
                groups.Add(group);
                parent = i == 5 ? null : group;
            }
            doc.Page     = doc.AddPage();
            doc.FontSize = 36;
            doc.Rect.Inset(20, 20);
            Page   page   = (Page)doc.ObjectSoup[doc.Page];
            Writer writer = new Writer(props, page);

            // This determines the nesting of actual visibility. Here we ensure that this
            // corresponds to the hierarchy specified in the UI so that it works in an
            // obvious way.
            for (int i = 0; i < groups.Count; i++)
            {
                Group group = groups[i];
                OptionalContent.Layer layer = writer.AddGroup(group);
                if (i == 5)
                {
                    while (writer.Depth > 0)
                    {
                        writer.EndLayer();
                    }
                }
                writer.StartLayer(layer);
                doc.AddText(group.EntryName.Text + "\r\n");
            }
            while (writer.Depth > 0)
            {
                writer.EndLayer();
            }
            doc.Flatten();
            LoadPDF(doc);
        }
示例#25
0
        public byte[] ExtractPages(byte[] documentBytes, int startingPageNumber, int pageCount)
        {
            byte[] extractedDocBytes;
            using (var srcDoc = new Doc())
            {
                srcDoc.Read(documentBytes);
                int srcPagesID = srcDoc.GetInfoInt(srcDoc.Root, "Pages");  //get the root page id
                int srcDocRot  = srcDoc.GetInfoInt(srcPagesID, "/Rotate"); //get the rotation of root setting

                using (var extractedPages = new Doc())
                {
                    for (var i = startingPageNumber; i < startingPageNumber + pageCount; i++)
                    {
                        srcDoc.PageNumber = i; //turn original file to current page

                        extractedPages.MediaBox.String = srcDoc.MediaBox.String;

                        extractedPages.AddPage();
                        extractedPages.PageNumber  = i - startingPageNumber + 1;
                        extractedPages.Rect.String = extractedPages.MediaBox.String;//doc2.Rect.String;

                        extractedPages.AddImageDoc(srcDoc, i, null);

                        //get the rotation of current page by page Id
                        int srcPageRot = srcDoc.GetInfoInt(srcDoc.Page, "/Rotate");

                        //rotate the page if any rotation exist
                        if (srcDocRot != 0)
                        {
                            extractedPages.SetInfo(extractedPages.Page, "/Rotate", srcDocRot);
                        }

                        if (srcPageRot != 0)
                        {
                            extractedPages.SetInfo(extractedPages.Page, "/Rotate", srcPageRot);
                        }
                    }
                    extractedDocBytes = extractedPages.GetData();
                    extractedPages.Clear();
                }

                srcDoc.Clear();
            }

            return(extractedDocBytes);
        }
示例#26
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);
        }
示例#27
0
        public IEnumerable <byte[]> SplitPdfPages(byte[] originalPdfBytes)
        {
            var pdfFiles = new List <byte[]>();

            using (var doc = new Doc())
            {
                doc.Read(originalPdfBytes);

                int srcPagesID = doc.GetInfoInt(doc.Root, "Pages");
                int srcDocRot  = doc.GetInfoInt(srcPagesID, "/Rotate");

                for (var i = 1; i <= doc.PageCount; i++)
                {
                    var singlePagePdf = new Doc();
                    doc.PageNumber = i;

                    singlePagePdf.Rect.String = singlePagePdf.MediaBox.String = doc.MediaBox.String;
                    singlePagePdf.AddPage();
                    singlePagePdf.AddImageDoc(doc, i, null);
                    singlePagePdf.FrameRect();

                    int srcPageRot = doc.GetInfoInt(doc.Page, "/Rotate");

                    if (srcDocRot != 0)
                    {
                        singlePagePdf.SetInfo(singlePagePdf.Page, "/Rotate", srcDocRot);
                    }

                    if (srcPageRot != 0)
                    {
                        singlePagePdf.SetInfo(singlePagePdf.Page, "/Rotate", srcPageRot);
                    }

                    var singlePagePdfBytes = singlePagePdf.GetData();
                    pdfFiles.Add(singlePagePdfBytes);

                    singlePagePdf.Clear();
                }
                doc.Clear();
            }

            return(pdfFiles);
        }
示例#28
0
        public List <string> Split(string filepath, int splitPageLength)
        {
            var listOfFiles = new List <string>();

            using (var originalDoc = new Doc())
            {
                originalDoc.Read(filepath);

                // Split into seperate certificates
                for (var i = 1; i <= originalDoc.PageCount; i += splitPageLength)
                {
                    int numberOfPagesToExtract;
                    if (i + splitPageLength - 1 > originalDoc.PageCount)
                    {
                        numberOfPagesToExtract = originalDoc.PageCount - i + 1;
                    }
                    else
                    {
                        numberOfPagesToExtract = splitPageLength;
                    }

                    using (var extractedDoc = new Doc())
                    {
                        for (var j = 0; j < numberOfPagesToExtract; j++)
                        {
                            originalDoc.PageNumber       = i + j;
                            extractedDoc.MediaBox.String = originalDoc.MediaBox.String;
                            extractedDoc.AddPage();
                            extractedDoc.PageNumber  = j + 1;
                            extractedDoc.Rect.String = extractedDoc.MediaBox.String;
                            extractedDoc.AddImageDoc(originalDoc, i + j, null);
                        }

                        var splitFilePath = Path.GetTempPath() + Guid.NewGuid() + ".pdf";
                        extractedDoc.Save(splitFilePath);
                        listOfFiles.Add(splitFilePath);
                    }
                }
            }

            return(listOfFiles);
        }
示例#29
0
        /// <summary>
        /// Move row content to the next page
        /// </summary>
        private void MoveRowToNextPage()
        {
            ArrayList oldRowObjects = new ArrayList(mOwnRowObjects);

            oldRowObjects.AddRange(mChildRowObjects);
            mOwnRowObjects.Clear();
            mChildRowObjects.Clear();

            if (PageNumber == mDoc.PageCount)
            {
                mDoc.Page = mDoc.AddPage();
            }
            else
            {
                PageNumber = PageNumber + 1;
            }

            mDoc.Rect.String = mBounds.String;
            mDoc.Rect.Top    = GetParentTopBounds();

            PagePos oldRowTop = RowTop;

            RowTop    = new PagePos(this);
            RowBottom = RowTop;
            double headerOffset = 0;

            if (RepeatHeader)
            {
                int posX = mPos.X;
                MoveRowToNextPage(mHeaderObjects, GetParentTopBounds() - mHeaderPos.PosY, false);
                if (FrameHeader)
                {
                    FrameRow(mPos.Y);
                }
                NextRow();
                mPos.X       = posX;
                headerOffset = mRowPositions[mPos.Y - 1].Top.PosY - mRowPositions[mPos.Y - 1].Bottom.PosY;
            }

            MoveRowToNextPage(oldRowObjects, GetParentTopBounds() - oldRowTop.PosY - headerOffset, true);
        }
示例#30
0
        private void createButton3_Click(object sender, EventArgs e)
        {
            Doc          doc    = new Doc();
            Properties   props  = Properties.FromDoc(doc, true);
            List <Group> groups = new List <Group>();

            for (int i = 1; i < 4; i++)
            {
                groups.Add(props.AddGroup("Layer " + i.ToString(), null));
            }
            // membership policies are simple to use but limited in scope
            MembershipGroup alloff = props.AddMembershipGroup();

            alloff.Policy       = MembershipGroup.PolicyEnum.AllOff;
            alloff.PolicyGroups = groups;
            // membership visibility expressions are more complex but more powerful
            MembershipGroup mgve = props.AddMembershipGroup();
            ArrayAtom       ve   = mgve.MakeVisibilityExpression(MembershipGroup.LogicEnum.Or, groups);

            mgve.EntryVE = mgve.MakeVisibilityExpression(MembershipGroup.LogicEnum.Not, new ArrayAtom[] { ve });
            doc.FontSize = 36;
            doc.Rect.Inset(20, 20);
            for (int i = 0; i < 3; i++)
            {
                doc.Page = doc.AddPage();
                Page   page   = (Page)doc.ObjectSoup[doc.Page];
                Writer writer = new Writer(props, page);
                OptionalContent.Layer layer1 = writer.AddGroup(alloff);
                doc.AddText("The next line uses a Policy so that it is only visible if all layers are turned off...\r\n");
                writer.StartLayer(layer1);
                doc.AddText("I am normally invisible\r\n\r\n");
                writer.EndLayer();
                OptionalContent.Layer layer2 = writer.AddGroup(mgve);
                doc.AddText("The next line uses a Visibility Expression so that it is only visible if all layers are turned off...\r\n");
                writer.StartLayer(layer2);
                doc.AddText("I am normally invisible\r\n");
                writer.EndLayer();
                doc.Flatten();
            }
            LoadPDF(doc);
        }
示例#31
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());
        }
示例#32
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();
        }
示例#33
0
        /// <summary>
        /// Converts an image file such as Tiff to PDF
        /// </summary>
        /// <param name="originalFileName">the file path and name with its extension</param>
        /// <returns>filepath and filename of the converted image file to a PDF file</returns>
        public string ConvertImageToPdf(string originalFileName)
        {
            try
            {
                if (!System.IO.File.Exists(originalFileName))
                {
                    return(string.Empty);
                }

                using (XImage theImg = new XImage())
                {
                    using (Doc theDoc = new Doc())
                    {
                        string filename = originalFileName.Remove(originalFileName.LastIndexOf(".")) + ".pdf";

                        theImg.SetFile(originalFileName);

                        for (int i = 1; i <= theImg.FrameCount; i++)
                        {
                            theImg.Frame = i;
                            theDoc.Page  = theDoc.AddPage();
                            theDoc.AddImageObject(theImg, false);
                        }

                        theImg.Clear();
                        theDoc.Save(filename);
                        theDoc.Clear();
                        return(filename);
                    }
                }
            }
            catch (Exception e)
            {
                //this.Log().Error(string.Format("Error converting image to Pdf: {0}", originalFileName), e);
                //Throw the stack trace with it.
                throw;
            }
        }
        /// <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();
        }
示例#35
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;
        }
    }
        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;
        }
示例#37
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);
        }
示例#38
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();
		}
        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();
        }
        /// <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;
        }
        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;
        }
示例#43
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();
            }
        }
示例#44
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);
        }
示例#45
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;
        }
 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();
 }
示例#48
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;
            }
        }
        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();
        }