public ActionResult GenerateMultiPdf(string a, string l, string resync)
        {
            var sep     = new[] { '|' };
            var ios     = a.Split(sep, StringSplitOptions.RemoveEmptyEntries);
            var lineNos = l.Split(sep, StringSplitOptions.RemoveEmptyEntries);

            if (ios.Any() && lineNos.Any() && ios.Count().Equals(lineNos.Count()))
            {
                var allDocs = new Doc();

                byte[] pdfs = null;

                for (var i = 0; i < ios.Count(); i++)
                {
                    CreateAndAppendDeliveryAssurancesPdf(Request, ios[i], Convert.ToInt32(lineNos[i]), resync == "1", ref allDocs, ref pdfs);
                }

                allDocs.ClearCachedDecompressedStreams();
                allDocs.Clear();
                allDocs.Dispose();

                if (pdfs != null)
                {
                    Response.AddHeader("Content-Disposition", "inline; filename=DeliveryAssurances.pdf");
                    return(File(pdfs, "application/pdf"));
                }
            }

            return(HttpNotFound());
        }
Exemple #2
0
        public static List <InvoiceAttachment> ConvertPdfToPng(string pathToDocument, string folderPath)
        {
            XSettings.InstallLicense(ConfigurationManager.AppSettings["ABCPdfKey"]);
            pathToDocument = LocalizePath(pathToDocument);

            var convertedFileName    = string.Empty;
            var convertedAttachments = new List <InvoiceAttachment>();
            var pdfToConvert         = new Doc();

            pdfToConvert.Read(pathToDocument);

            // loop through the pages

            var n = pdfToConvert.PageCount;

            for (var i = 1; i <= n; i++)
            {
                pdfToConvert.PageNumber  = i;
                pdfToConvert.Rect.String = pdfToConvert.CropBox.String;
                convertedFileName        = $"{folderPath}\\{Path.GetFileNameWithoutExtension(pathToDocument)}{i}.png";
                pdfToConvert.Rendering.Save(convertedFileName);
                var newDoc = new InvoiceAttachment
                {
                    DocumentPath = convertedFileName
                };
                convertedAttachments.Add(newDoc);
                newDoc = null;
            }
            pdfToConvert.Clear();
            return(convertedAttachments);
        }
Exemple #3
0
        public void Merge(string parentFile, IEnumerable <string> filesToMerge)
        {
            var outputPdfDoc = new Doc();

            if (File.Exists(parentFile))
            {
                outputPdfDoc.Read(parentFile);
            }

            try
            {
                foreach (string file in filesToMerge)
                {
                    var inputPdfDoc = new Doc();
                    inputPdfDoc.Read(file);
                    outputPdfDoc.Append(inputPdfDoc);
                    inputPdfDoc.Clear();
                    inputPdfDoc.Dispose();
                }

                outputPdfDoc.Save(parentFile);
            }
            finally
            {
                outputPdfDoc.Clear();
                outputPdfDoc.Dispose();
            }
        }
Exemple #4
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();
        }
    }
Exemple #5
0
        /// <summary>
        /// Applies the first page of the PDF file located at waterMarkImagePdfPath as a watermark
        /// to each page of the PDF file located at inputFilePath
        /// </summary>
        /// <param name="inputFilePath">File path of document to be watermarked</param>
        /// <param name="waterMarkImagePdfPath">File path of watermark template</param>
        public void AddWatermark(string inputFilePath, string waterMarkImagePdfPath)
        {
            var temp = inputFilePath + ".watermark";

            var watermarkImage = this.ConvertSinglePdfPageToJpegImage(waterMarkImagePdfPath, 1);

            using (var doc = new Doc())
            {
                doc.Read(inputFilePath);
                int theCount = doc.PageCount;

                int theID = 0;
                for (int i = 1; i <= theCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Layer      = doc.LayerCount + 1;
                    if (i == 1)
                    {
                        theID = doc.AddImageFile(watermarkImage.FullName, 1);
                    }
                    else
                    {
                        doc.AddImageCopy(theID);
                    }
                }
                doc.Save(temp);
                doc.Clear();
                doc.Dispose();
            }

            File.Delete(inputFilePath);
            File.Move(temp, inputFilePath);
            File.Delete(watermarkImage.FullName);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            //not working

            XSettings.Register();
            XSettings.InstallLicense("cd9b5c07db69df2bf57c0a04d9bca58b10c44889c9fb197984e592f49addfce5ec5fe85d7b9205bc");
            XSettings.InstallSystemLicense("cd9b5c07db69df2bf57c0a04d9bca58b10c44889c9fb197984e592f49addfce5ec5fe85d7b9205bc");
            XSettings.InstallRedistributionLicense("cd9b5c07db69df2bf57c0a04d9bca58b10c44889c9fb197984e592f49addfce5ec5fe85d7b9205bc");
            XSettings.InstallTrialLicense("cd9b5c07db69df2bf57c0a04d9bca58b10c44889c9fb197984e592f49addfce5ec5fe85d7b9205bc");
            XSettings.Register();
            Doc theDoc = new Doc();

            theDoc.FontSize = 72;
            theDoc.AddTextStyled("<b>Gallia</b> est omnis divisa in partes tres, quarum unam incolunt <b>Belgae</b>, aliam <b>Aquitani</b>, tertiam qui ipsorum lingua <b>Celtae</b>, nostra <b>Galli</b> appellantur.");
            theDoc.Save("../../testingC.pdf"); //need licence
            theDoc.Clear();

            Signature theSig = (Signature)theDoc.Form["Signature"];

            theSig.Location = "here";
            theSig.Reason   = "test";
            //pfx + password
            theSig.Sign("../../../test.pfx", "123456");
            theDoc.Save("../../testingC signed.pdf");
        }
        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();
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            Doc theDoc = new Doc();

            theDoc.AddImageUrl("http://www.google.com/");
            theDoc.Save(Server.MapPath("htmlimport.pdf"));
            theDoc.Clear();
        }
Exemple #9
0
        public FileInfo ConvertPdfFirstPageToImage(byte[] originalPdfBytes)
        {
            string filename;

            using (var doc = new Doc())
            {
                doc.Read(originalPdfBytes);
                var op = new ImageOperation(doc);
                op.PageContents.AddPages();

                var firstImage = (from parent in op.GetImageProperties()
                                  from child in parent.Renditions
                                  join page in doc.ObjectSoup.Catalog.Pages.GetPageArray() on child.PageID equals page.ID
                                  orderby page.PageNumber
                                  select parent.PixMap).First();

                switch (firstImage.Compression)
                {
                case CompressionType.Ccitt:
                    filename = Path.GetTempFileName() + firstImage.ID + ".tiff";
                    using (var tiff = Tiff.Open(filename, "w"))
                    {
                        tiff.SetField(TiffTag.IMAGEWIDTH, firstImage.Width.ToString());
                        tiff.SetField(TiffTag.IMAGELENGTH, firstImage.Height.ToString());
                        tiff.SetField(TiffTag.COMPRESSION, XRendering.Compression.G4);
                        tiff.SetField(TiffTag.BITSPERSAMPLE, firstImage.BitsPerComponent.ToString());
                        tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                        tiff.WriteRawStrip(0, firstImage.GetData(), firstImage.Length);
                        tiff.Close();
                    }

                    // Resave the image to change its compression (which is better for the OCR engine)
                    System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
                    var newFilename          = filename.Replace(".tiff", "_resaved.tiff");
                    img.Save(newFilename, System.Drawing.Imaging.ImageFormat.Tiff);
                    img.Dispose();

                    // Delete the original
                    File.Delete(filename);
                    filename = newFilename;

                    break;

                case CompressionType.Jpeg:
                    filename = Path.GetTempFileName() + firstImage.ID + ".jpg";
                    File.WriteAllBytes(filename, firstImage.GetData());
                    break;

                default:
                    throw new NotSupportedException("PDF Image Extraction: File type not supported.");
                }
                doc.Clear();
            }
            return(new FileInfo(filename));
        }
Exemple #10
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;
        }
    }
 public ActionResult ExportPdf()
 {
     StreamReader sr = new StreamReader(@"D:\Code\C#\SmallDragon\SmallDragon\Temp\HtmlPage3.html");
     string html = sr.ReadToEnd();
     Doc doc = new Doc();
     doc.AddImageHtml(html);
     doc.Save(@"C:\Users\GuyFawkes\Desktop\New folder\out.pdf");
     doc.Clear();
     System.Diagnostics.Process.Start(@"C:\Users\GuyFawkes\Desktop\New folder\out.pdf");
     return View("Index");
 }
        private static void Main(string[] args)
        {
            // install your own licence

            using (Doc doc = new Doc())
            {
                doc.Read("in.pdf"); // in this PDF the image has an embedded ICC profile, and I must remove them

                Console.WriteLine("################################ THROUGH GETINFO ################################");

                // Remove the ICC profiles through Get/SetInfo methods
                foreach (var item in doc.ObjectSoup)
                {
                    if (item != null && doc.GetInfo(item.ID, "/ColorSpace*[0]*:Name").Equals("ICCBased", StringComparison.InvariantCultureIgnoreCase))
                    {
                        int profileId = doc.GetInfoInt(item.ID, "/ColorSpace*[1]:Ref"); // note the [1]: why is it there?
                        if (profileId != 0)
                        {
                            doc.GetInfo(profileId, "Decompress");
                            string profileData = doc.GetInfo(profileId, "Stream");

                            // this outputs the ICC profile raw data, with the profile's name somewhere up top
                            Console.WriteLine(string.Format("ICC profile for object ID {0}: {1}", item.ID, profileData)); 

                            doc.SetInfo(profileId, "Stream", string.Empty);
                            doc.GetInfo(profileId, "Compress");
                        }
                    }
                }

                doc.Save("out-infos.pdf");
                doc.Clear();
                doc.Read("in.pdf");

                Console.WriteLine("################################ THROUGH OBJECTS ################################");

                // Remove ICC profiles through the pixmap objects
                foreach (var item in doc.ObjectSoup)
                {
                    if (doc.GetInfo(item.ID, "Type") == "jpeg") // only work on PixMaps
                    {
                        PixMap pm = (PixMap)item;
                        if (pm.ColorSpaceType == ColorSpaceType.ICCBased)
                        {
                            // pm.ColorSpace.IccProfile is always null so I can't really set it to null or Recolor() it because it would change noting
                            Console.WriteLine(string.Format("ICC profile for object ID {0}: {1}", item.ID, pm.ColorSpace.IccProfile)); // there should already be an ICC profile (ColorSpaceType = ICCBased) so why does ColorSpace.IccProfile creates one ?
                        }
                    }
                }

                doc.Save("out-objects.pdf");
            }
        }
Exemple #13
0
        /// <summary>
        /// Saves a MemoryStream containing an XPS document to a PDF document
        /// </summary>
        /// <param name="xpsMemoryStream">Stream containing an XPS document</param>
        /// <param name="targetPath">Full target path and file name with .PDF extension</param>
        public void SaveXpsStreamAsPdf(MemoryStream xpsMemoryStream, string targetPath)
        {
            var pdfDoc = new Doc();

            pdfDoc.Read(xpsMemoryStream, new XReadOptions()
            {
                ReadModule = ReadModuleType.Xps
            });
            pdfDoc.Save(targetPath);
            pdfDoc.Clear();
            xpsMemoryStream.Close();
        }
        public void Control()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["LicenseKey"].ConnectionString;
            XSettings.InstallLicense(connectionString);
            var theDoc = new Doc { FontSize = 96 };

            theDoc.AddText("Control");
            Response.ContentType = "application/pdf";
            theDoc.Save(Response.OutputStream);
            theDoc.Clear();
            theDoc.Dispose();
        }
    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;
        }
    }
        public bool ConvertToImage(string pdfPath, string toSaveImagePath, ILogger logger, bool hideSection, List <RectangleDimesion> rectangles, List <RectangleDimesion> highQualityRectangles = null)
        {
            if (pdfPath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                return(false);
            }
            if (toSaveImagePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                return(false);
            }

            if (File.Exists(pdfPath))
            {
                var    doc          = new Doc();
                string tempSavePath = hideSection ? Directory.GetParent(toSaveImagePath).FullName + "\\temp.jpg" : toSaveImagePath;

                try
                {
                    doc.Read(pdfPath);
                    doc.PageNumber = 1;
                    doc.Rendering.Save(tempSavePath);
                }
                catch (Exception ex)
                {
                    logger.Error("System Failure! File could not be generated. Message: " + ex.Message + " \n\t " +
                                 ex.StackTrace);
                    return(false);
                }
                finally
                {
                    doc.ClearCachedDecompressedStreams();
                    doc.Clear();
                    doc.Dispose();
                }

                if (hideSection)
                {
                    HideEcgFinding(tempSavePath, toSaveImagePath, logger, rectangles);
                }

                var imageName = _settings.HighImageQuality + Path.GetFileName(toSaveImagePath);

                var directoryToSave  = Directory.GetParent(toSaveImagePath).FullName;
                var highQualityImage = Path.Combine(directoryToSave, imageName);

                ConvertToHighQualityImage(pdfPath, highQualityImage, logger, hideSection, highQualityRectangles);

                return(true);
            }
            return(false);
        }
        private Stream ConvertPdfToImage(string url, int marginLeft, int marginTop, int page)
        {
            Stream returnStream = null;

            byte[] buffer = new byte[4096];
            int    count  = 0;

            byte[] pdfBytes = null;
            XSettings.InstallRedistributionLicense(System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]);


            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; // Enalbe SVG
                theDoc.HtmlOptions.UseVideo         = true;
                theDoc.HtmlOptions.PageCacheEnabled = true; //Enable cache
                theDoc.HtmlOptions.Timeout          = 120000;
                theDoc.Rect.Inset(marginLeft, marginTop);
                theDoc.Read(pdfBytes);
                theDoc.PageNumber            = page;
                theDoc.Rendering.DotsPerInch = constDotPerInches;
                theDoc.Rendering.SaveQuality = constSaveQuality;
                theDoc.Flatten();

                //Each page of pdf will be returned as a byte array

                byte[] images = theDoc.Rendering.GetData("abc.png");
                returnStream = new MemoryStream(images);
                theDoc.Clear();
            }
            return(returnStream);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // ---- Adds a font reference to the document ----
            Doc doc = new Doc();

            doc.FontSize = 48;
            string theFont = "Times-Roman ";

            doc.Font = doc.AddFont(theFont);
            doc.AddText(theFont);
            theFont  = "Helvetica-Bold";
            doc.Font = doc.AddFont(theFont);
            doc.AddText(theFont);
            doc.Save(Server.MapPath("~/Results/Output.pdf"));
            doc.Clear();
        }
        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);
        }
Exemple #20
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);
        }
Exemple #21
0
 private static void AppendPdf(Doc finalReport, string sourceDocPath)
 {
     if (!string.IsNullOrEmpty(sourceDocPath))
     {
         var sourceDocPdfDoc = new Doc();
         try
         {
             sourceDocPdfDoc.Read(sourceDocPath);
             finalReport.Append(sourceDocPdfDoc);
         }
         finally
         {
             sourceDocPdfDoc.Clear();
             sourceDocPdfDoc.Dispose();
         }
     }
 }
Exemple #22
0
        public FileInfo ConvertSinglePdfPageToJpegImage(string filepath, int pageNumber)
        {
            var filename = Path.GetTempPath() + Guid.NewGuid() + ".jpg";

            using (var doc = new Doc())
            {
                doc.Read(filepath);
                doc.PageNumber            = pageNumber;
                doc.Rect.String           = doc.CropBox.String;
                doc.Rendering.DotsPerInch = 300;
                doc.Rendering.SaveQuality = 100;
                doc.Rendering.Save(filename);
                doc.Clear();
            }

            return(new FileInfo(filename));
        }
Exemple #23
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;
            }
        }
Exemple #24
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);
        }
Exemple #25
0
        public void SavePDF(Doc theDoc)
        {
            Random R = new Random();

            byte[]         theData = theDoc.GetData();
            CommonFunction cf      = new CommonFunction();

            Response.Clear();
            Response.AddHeader("content-type", "application/pdf");
            Response.AddHeader("content-disposition", "inline; filename='Brochure" + "_" + R.Next(1000).ToString() + ".pdf'");
            if (Context.Response.IsClientConnected)
            {
                Session.Abandon();
                Context.Response.OutputStream.Write(theData, 0, theData.Length);
                Context.Response.Flush();
            }
            theDoc.Clear();
        }
        public ActionResult GenerateDryingAgrementPdf(string resync = "true")
        {
            var theDoc = new Doc();

            var pdf = CreateDryingAgreementPdf(Request, resync == "true", ref theDoc);

            theDoc.ClearCachedDecompressedStreams();
            theDoc.Clear();
            theDoc.Dispose();

            if (pdf == null)
            {
                return(HttpNotFound());
            }

            Response.AddHeader("Content-Disposition", "inline; filename=DryingAgreement.pdf");
            return(File(pdf, "application/pdf"));
        }
Exemple #27
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();
        }
        private void CreateAndAppendDeliveryAssurancesPdf(HttpRequestBase request, string id, int lineNumber, bool resync, ref Doc allDocs, ref byte[] pdfOut)
        {
            var theDoc = new Doc();

            CreateDeliveryAssurancePdf(request, id, lineNumber, resync, ref theDoc);

            if (allDocs == null)
            {
                allDocs = new Doc();
            }

            allDocs.Append(theDoc);

            pdfOut = allDocs.GetData();

            theDoc.ClearCachedDecompressedStreams();
            theDoc.Clear();
            theDoc.Dispose();
        }
Exemple #29
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);
        }
Exemple #30
0
 /// <summary>
 /// Stamps a PDF document with a line of text in a small font size at the lower left hand side of
 /// the first page of the document
 /// </summary>
 /// <param name="documentPath">The full PDF document file path and name</param>
 /// <param name="text">The line of text to stamp onto the document</param>
 public void AddFooterText(string path, string text)
 {
     using (var doc = new Doc())
     {
         doc.Read(path);
         using (var doc2 = new Doc())
         {
             doc2.Read(doc.GetStream());
             doc.Clear();
             doc2.FontSize = 8;
             var theF1 = doc2.AddFont("Arial");
             doc2.Font  = theF1;
             doc2.Pos.X = 37;
             doc2.Pos.Y = 32;
             doc2.AddText(text);
             doc2.Save(path);
         }
     }
 }
Exemple #31
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);
        }
Exemple #32
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;
            }
        }
Exemple #33
0
        public void SavePdfAsTiffImage(string source, string destinationForTiff)
        {
            Doc theDoc = null;

            try
            {
                theDoc = new Doc();
                theDoc.Read(source);

                // set up the rendering parameters

                theDoc.Rendering.ColorSpace = XRendering.ColorSpaceType.Gray;

                theDoc.Rendering.BitsPerChannel = 8;

                theDoc.Rendering.DotsPerInch = 200;

                var pageCount = theDoc.PageCount;

                for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++)
                {
                    theDoc.PageNumber = pageNumber;

                    theDoc.Rect.String = theDoc.CropBox.String;

                    theDoc.Rendering.SaveAppend = (pageNumber != 1);

                    theDoc.Rendering.SaveCompression = XRendering.Compression.LZW;

                    theDoc.Rendering.Save(destinationForTiff);
                }
            }
            finally
            {
                theDoc.Clear();
                theDoc.Dispose();
            }
        }
        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();
        }
        public ActionResult GeneratePdf(string a, string l, string resync)
        {
            var ioNumber = a;
            int lineNumber;

            if (!string.IsNullOrWhiteSpace(ioNumber) && !string.IsNullOrWhiteSpace(l) && int.TryParse(l, out lineNumber))
            {
                var theDoc = new Doc();

                var pdf = CreateDeliveryAssurancePdf(Request, ioNumber, lineNumber, resync == "true", ref theDoc);

                theDoc.ClearCachedDecompressedStreams();
                theDoc.Clear();
                theDoc.Dispose();

                if (pdf != null)
                {
                    Response.AddHeader("Content-Disposition", "inline; filename=DeliveryAssurance.pdf");
                    return(File(pdf, "application/pdf"));
                }
            }

            return(HttpNotFound());
        }
Exemple #36
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);
        }
    }
Exemple #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);
        }
        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();

        }
        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 Stream ConvertPdfToImage(string url, int marginLeft, int marginTop, int page)
        {
            Stream returnStream = null;

            byte[] buffer = new byte[4096];
            int count = 0;
            byte[] pdfBytes = null;
            XSettings.InstallRedistributionLicense(System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]);

            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; // Enalbe SVG
                theDoc.HtmlOptions.UseVideo = true;
                theDoc.HtmlOptions.PageCacheEnabled = true; //Enable cache
                theDoc.HtmlOptions.Timeout = 120000;
                theDoc.Rect.Inset(marginLeft, marginTop);
                theDoc.Read(pdfBytes);
                theDoc.PageNumber = page;
                theDoc.Rendering.DotsPerInch = constDotPerInches;
                theDoc.Rendering.SaveQuality = constSaveQuality;
                theDoc.Flatten();

                //Each page of pdf will be returned as a byte array

                byte[] images = theDoc.Rendering.GetData("abc.png");
                returnStream = new MemoryStream(images);
                theDoc.Clear();
            }
            return returnStream;
        }
        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;
        }
Exemple #42
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;
            }
        }
Exemple #43
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;
            }
        }
Exemple #44
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);
            }
        //}
    }
Exemple #45
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();
		}
    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;
        }
    }
        /// <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;
        }