Пример #1
2
 private void SaveHtmlAsPdf(string fName, string html)
 {
     GlobalConfig cfg = new GlobalConfig();
     SimplePechkin sp = new SimplePechkin(cfg);
     ObjectConfig oc = new ObjectConfig();
     oc.SetCreateExternalLinks(true)
         .SetFallbackEncoding(Encoding.ASCII)
         .SetLoadImages(true)
         .SetAllowLocalContent(true)
         .SetPrintBackground(true);
     
     byte[] pdfBuf = sp.Convert(oc, "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>" + html + "</body></html>");
     FileStream fs = new FileStream(fName, FileMode.Create, FileAccess.ReadWrite);
     foreach (var byteSymbol in pdfBuf)
         fs.WriteByte(byteSymbol);
     fs.Close();
 }
Пример #2
0
        private static byte[] ToPdf(string xml)
        {
            // create global configuration object
            GlobalConfig gc = new GlobalConfig();

            // set it up using fluent notation
            gc.SetDocumentTitle("DeadFolder certificate").SetPaperSize(PaperKind.A4Rotated);

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

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

            // and set it up using fluent notation too
            oc.SetCreateExternalLinks(false)
                .SetPrintBackground(true)
                .SetFallbackEncoding(Encoding.ASCII)
                .SetLoadImages(true)
                .SetIntelligentShrinking(true);
            //... etc

            // convert document
            return pechkin.Convert(oc, xml);
        }
Пример #3
0
        /// <summary>
        /// Runs conversion process.
        ///
        /// Allows to convert both external HTML resource and HTML string.
        ///
        /// Takes html source as a byte array for when you don't know the encoding.
        /// </summary>
        /// <param name="doc">document parameters</param>
        /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param>
        /// <returns>PDF document body</returns>
        public byte[] Convert(ObjectConfig doc, byte[] html)
        {
            this.CreateConverter();

            // create unmanaged object config
            IntPtr objConf = doc.CreateObjectConfig();

            Tracer.Trace("T:" + Thread.CurrentThread.Name + " Created object config");

            // add object to converter
            PechkinStatic.AddObject(this._converter, objConf, html);

            Tracer.Trace("T:" + Thread.CurrentThread.Name + " Added object to converter");

            // run OnBegin
            this.OnBegin(_converter);

            // run conversion process
            if (!PechkinStatic.PerformConversion(this._converter))
            {
                Tracer.Trace("T:" + Thread.CurrentThread.Name + " Conversion failed, null returned");

                return(null);
            }

            // get output
            return(PechkinStatic.GetConverterResult(this._converter));
        }
Пример #4
0
        public byte[] Convert(ObjectConfig doc)
        {
            Func <object> del = () =>
            {
                return(this.remoteInstance.Convert(doc));
            };

            return(this.Invoke(del) as byte[]);
        }
Пример #5
0
        /// <summary>
        /// Runs conversion process.
        ///
        /// Allows to convert both external HTML resource and HTML string.
        ///
        /// Takes html source as a byte array for when you don't know the encoding.
        /// </summary>
        /// <param name="doc">document parameters</param>
        /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param>
        /// <returns>PDF document body</returns>
        public byte[] Convert(ObjectConfig doc, byte[] html)
        {
            if (_reinitConverter)
            {
                CreateConverter();
            }

            // create unmanaged object config
            IntPtr objConf = doc.CreateObjectConfig();

            if (_log.IsTraceEnabled)
            {
                _log.Trace("T:" + Thread.CurrentThread.Name + " Created object config");
            }

            // add object to converter
            PechkinStatic.AddObject(_converter, objConf, html);

            if (_log.IsTraceEnabled)
            {
                _log.Trace("T:" + Thread.CurrentThread.Name + " Added object to converter");
            }

            // run OnBegin
            OnBegin(_converter);

            try
            {
                // run conversion process
                if (!PechkinStatic.PerformConversion(_converter))
                {
                    if (_log.IsTraceEnabled)
                    {
                        _log.Trace("T:" + Thread.CurrentThread.Name + " Conversion failed, null returned");
                    }

                    return(null);
                }

                // get output
                return(PechkinStatic.GetConverterResult(_converter));
            }
            finally
            {
                // next time we'll need a new one, but for now we'll preserve the old one for the properties (such as http error code)
                // to work properly
                _reinitConverter = true;
            }
        }
Пример #6
0
 /// <summary>
 /// Converts external HTML resource into PDF.
 /// </summary>
 /// <param name="doc">document parameters, <code>ObjectConfig.SetPageUri</code> should be set</param>
 /// <returns>PDF document body</returns>
 public byte[] Convert(ObjectConfig doc)
 {
     return(Convert(doc, (byte[])null));
 }
Пример #7
0
 /// <summary>
 /// Runs conversion process.
 ///
 /// Allows to convert both external HTML resource and HTML string.
 /// </summary>
 /// <param name="doc">document parameters</param>
 /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param>
 /// <returns>PDF document body</returns>
 public byte[] Convert(ObjectConfig doc, string html)
 {
     return(Convert(doc, Encoding.UTF8.GetBytes(html)));
 }
Пример #8
0
        public byte[] Convert(ObjectConfig doc)
        {
            Func<object> del = () =>
            {
                return this.remoteInstance.Convert(doc);
            };

            return this.Invoke(del) as byte[];
        }
Пример #9
0
 /// <summary>
 /// Converts external HTML resource into PDF.
 /// </summary>
 /// <param name="doc">document parameters, <code>ObjectConfig.SetPageUri</code> should be set</param>
 /// <returns>PDF document body</returns>
 public byte[] Convert(ObjectConfig doc)
 {
     return Convert(doc, (byte[])null);
 }
Пример #10
0
 /// <summary>
 /// Runs conversion process.
 /// 
 /// Allows to convert both external HTML resource and HTML string.
 /// </summary>
 /// <param name="doc">document parameters</param>
 /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param>
 /// <returns>PDF document body</returns>
 public byte[] Convert(ObjectConfig doc, string html)
 {
     return Convert(doc, Encoding.UTF8.GetBytes(html));
 }
Пример #11
0
        /// <summary>
        /// Runs conversion process.
        /// 
        /// Allows to convert both external HTML resource and HTML string.
        /// 
        /// Takes html source as a byte array for when you don't know the encoding.
        /// </summary>
        /// <param name="doc">document parameters</param>
        /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param>
        /// <returns>PDF document body</returns>
        public byte[] Convert(ObjectConfig doc, byte[] html)
        {
            if (_reinitConverter)
            {
                CreateConverter();
            }

            // create unmanaged object config
            IntPtr objConf = doc.CreateObjectConfig();

            if (_log.IsTraceEnabled)
                _log.Trace("T:" + Thread.CurrentThread.Name + " Created object config");

            // add object to converter
            PechkinStatic.AddObject(_converter, objConf, html);

            if (_log.IsTraceEnabled)
                _log.Trace("T:" + Thread.CurrentThread.Name + " Added object to converter");

            // run OnBegin
            OnBegin(_converter);

            try
            {
                // run conversion process
                if (!PechkinStatic.PerformConversion(_converter))
                {
                    if (_log.IsTraceEnabled)
                        _log.Trace("T:" + Thread.CurrentThread.Name + " Conversion failed, null returned");

                    return null;
                }

                // get output
                return PechkinStatic.GetConverterResult(_converter);
            }
            finally
            {
                // next time we'll need a new one, but for now we'll preserve the old one for the properties (such as http error code)
                // to work properly
                _reinitConverter = true;
            }
        }
Пример #12
0
 internal object Convert(ObjectConfig objectConfig)
 {
     throw new NotImplementedException();
 }
Пример #13
0
        /// <summary>
        /// Runs conversion process.
        /// 
        /// Allows to convert both external HTML resource and HTML string.
        /// 
        /// Takes html source as a byte array for when you don't know the encoding.
        /// </summary>
        /// <param name="doc">document parameters</param>
        /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param>
        /// <returns>PDF document body</returns>
        public byte[] Convert(ObjectConfig doc, byte[] html)
        {
            CreateConverter();

            // create unmanaged object config
            IntPtr objConf = doc.CreateObjectConfig();

            if (_log.IsTraceEnabled)
                _log.Trace("T:" + Thread.CurrentThread.Name + " Created object config");

            // add object to converter
            PechkinStatic.AddObject(_converter, objConf, html);

            if (_log.IsTraceEnabled)
                _log.Trace("T:" + Thread.CurrentThread.Name + " Added object to converter");

            // run OnBegin
            OnBegin(_converter);

            // run conversion process
            if (!PechkinStatic.PerformConversion(_converter))
            {
                if (_log.IsTraceEnabled)
                    _log.Trace("T:" + Thread.CurrentThread.Name + " Conversion failed, null returned");

                return null;
            }

            // get output
            return PechkinStatic.GetConverterResult(_converter);
        }
Пример #14
-1
        public static void CreatePdfFromHtml(string htmlFilePath)
        {
            var htmlFileInfo = new FileInfo(htmlFilePath);

            if (!htmlFileInfo.Exists)
            {
                throw new FileNotFoundException(htmlFileInfo.FullName);
            }

            Debug.Assert(htmlFileInfo.DirectoryName != null, "htmlFileInfo.DirectoryName != null");

            var tmpPdfFileInfo = new FileInfo(Path.Combine(htmlFileInfo.DirectoryName, "tmp.pdf"));
            var pdfOutFileInfo = new FileInfo(GetPdfEquivalentPath(htmlFileInfo.FullName));

            var gc = new GlobalConfig();

            gc.SetImageQuality(100);
            gc.SetOutputDpi(96);
            gc.SetPaperSize(1024, 1123);

            var oc = new ObjectConfig();

            oc.SetLoadImages(true);
            oc.SetAllowLocalContent(true);
            oc.SetPrintBackground(true);
            oc.SetZoomFactor(1.093);
            oc.SetPageUri(htmlFileInfo.FullName);

            if (tmpPdfFileInfo.Exists)
            {
                tmpPdfFileInfo.Delete();
            }

            IPechkin pechkin = new SynchronizedPechkin(gc);

            pechkin.Error += (converter, text) =>
                {
                    Console.Out.WriteLine("error " + text);
                };

            pechkin.Warning += (converter, text) =>
                {
                    Console.Out.WriteLine("warning " + text);
                };

            using (var file = File.OpenWrite(tmpPdfFileInfo.FullName))
            {
                var bytes = pechkin.Convert(oc);
                file.Write(bytes, 0, bytes.Length);
            }

            if (pdfOutFileInfo.Exists)
            {
                pdfOutFileInfo.Delete();
            }

            CreateDirectories(pdfOutFileInfo.DirectoryName);

            tmpPdfFileInfo.MoveTo(pdfOutFileInfo.FullName);
        }
Пример #15
-1
        public bool SaveMultipleReceipts(int month, int year)
        {
            try
            {
                var receipts = _dal.SaveMultipleReceipts(month, year);

                var path = HttpContext.Current.Server.MapPath("~/receiptTemplate.html");
                var template = File.ReadAllText(path);

                var zipPath = string.Format("{0}\\receipts_{1}_{2}.zip", HttpContext.Current.Server.MapPath("~/exports"), month, year);
                var sourceZip = ZipFile.Create(zipPath);
                sourceZip.BeginUpdate();

                var gc = new GlobalConfig();
                gc.SetPaperSize(kind: PaperKind.A4);

                var margins = new Margins(30, 30, 30, 30);
                gc.SetMargins(margins);
                var pechkin = Factory.Create(gc);
                var objConfig = new ObjectConfig();
                objConfig.SetLoadImages(true);
                objConfig.SetPrintBackground(true);
                objConfig.SetScreenMediaType(true);
                objConfig.SetCreateExternalLinks(true);
                var fileList = new List<string>();
                foreach (var r in receipts)
                {
                    var receiptTemplate = template;
                    receiptTemplate = receiptTemplate.Replace("{indexNumber}", r.Receipt.IndexNumber.ToString());
                    receiptTemplate = receiptTemplate.Replace("{total}", r.Receipt.TotalAmount.ToString());
                    receiptTemplate = receiptTemplate.Replace("{vat}", r.Receipt.VatAmount.ToString());
                    receiptTemplate = receiptTemplate.Replace("{vatpercent}", ConfigurationManager.AppSettings["DefaultVatPercent"]);
                    receiptTemplate = receiptTemplate.Replace("{net}", r.Receipt.NetAmount.ToString());
                    receiptTemplate = receiptTemplate.Replace("{firstName}", r.Client.FirstName);
                    receiptTemplate = receiptTemplate.Replace("{lastName}", r.Client.LastName);
                    receiptTemplate = receiptTemplate.Replace("{address}", r.Client.Address);
                    receiptTemplate = receiptTemplate.Replace("{jobTitle}", r.Client.Title);
                    receiptTemplate = receiptTemplate.Replace("{afm}", r.Client.AFM);
                    receiptTemplate = receiptTemplate.Replace("{doy}", r.Client.DOY);
                    receiptTemplate = receiptTemplate.Replace("{desciption}", r.Receipt.ReceiptDescription);
                    receiptTemplate = receiptTemplate.Replace("{date}", r.Receipt.Date.ToString("dd-MM-yyyy"));

                    gc.SetDocumentTitle(r.Client.Address.Replace(".", "_"));
                    var pdf = pechkin.Convert(objConfig, receiptTemplate);
                    r.Client.Address = r.Client.Address.Replace(@"/", "-").Replace(@"\", "-");
                    r.Client.AdministrationOffice = r.Client.AdministrationOffice.Replace(@"/", "-").Replace(@"\", "-");
                    var filename = string.Format("{0}\\{1}_{2}{3}.pdf", HttpContext.Current.Server.MapPath("~/exports"),
                        r.Client.IndexNumber, r.Client.Address, (!String.IsNullOrEmpty(r.Client.AdministrationOffice) ? "_" + r.Client.AdministrationOffice : ""));
                    File.WriteAllBytes(filename, pdf);
                    fileList.Add(filename);
                    sourceZip.Add(new StaticDiskDataSource(filename), Path.GetFileName(filename), CompressionMethod.Deflated, true);
                }

                sourceZip.CommitUpdate();
                sourceZip.Close();

                foreach (var file in fileList)
                {
                    File.Delete(file);
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private byte[] CreatePDF(HtmlDocument doc)
        {
            // Create global configuration object
            GlobalConfig gc = new GlobalConfig();

            // Set it up using fluent notation
            gc.SetMargins(new Margins(50, 100, 0, 0))
                .SetDocumentTitle("Request")
                .SetPaperSize(PaperKind.A4);

            // Create converter
            IPechkin pechkin = new SimplePechkin(gc);

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

            // And set it up using fluent notation
            oc.SetCreateExternalLinks(true)
                .SetFallbackEncoding(Encoding.ASCII)
                .SetZoomFactor(2)
                .SetIntelligentShrinking(true)
                .SetLoadImages(true);

            // Convert document
            return pechkin.Convert(oc, doc.DocumentNode.OuterHtml);
        }
Пример #17
-1
        public HttpResponseMessage PrintReceipt(string receiptId)
        {
            var path = HttpContext.Current.Server.MapPath("~/receiptTemplate.html");
            var template = File.ReadAllText(path);

            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var receipt = _dal.GetReceipt(Convert.ToInt32(receiptId));
            var client = _dal.GetClient(receipt.ClientId);
            var receiptTemplate = template;
            receiptTemplate = receiptTemplate.Replace("{indexNumber}", receipt.IndexNumber.ToString());
            receiptTemplate = receiptTemplate.Replace("{total}", receipt.TotalAmount.ToString());
            receiptTemplate = receiptTemplate.Replace("{vat}", receipt.VatAmount.ToString());
            receiptTemplate = receiptTemplate.Replace("{vatpercent}", receipt.VatPercent.ToString());
            receiptTemplate = receiptTemplate.Replace("{net}", receipt.NetAmount.ToString());
            receiptTemplate = receiptTemplate.Replace("{firstName}", client.FirstName);
            receiptTemplate = receiptTemplate.Replace("{lastName}", client.LastName);
            receiptTemplate = receiptTemplate.Replace("{address}", client.Address);
            receiptTemplate = receiptTemplate.Replace("{jobTitle}", client.Title);
            receiptTemplate = receiptTemplate.Replace("{afm}", client.AFM);
            receiptTemplate = receiptTemplate.Replace("{doy}", client.DOY);
            receiptTemplate = receiptTemplate.Replace("{desciption}", receipt.ReceiptDescription);
            receiptTemplate = receiptTemplate.Replace("{date}", receipt.Date.ToString("dd-MM-yyyy"));

            var gc = new GlobalConfig();
            gc.SetPaperSize(kind: PaperKind.A4);
            gc.SetDocumentTitle(client.Address.Replace(".", "_"));
            var margins = new Margins(30, 30, 30, 30);
            gc.SetMargins(margins);

            var pechkin = Factory.Create(gc);
            var objConfig = new ObjectConfig();
            objConfig.SetLoadImages(true);
            objConfig.SetPrintBackground(true);
            objConfig.SetScreenMediaType(true);
            objConfig.SetCreateExternalLinks(true);
            //objConfig.Footer.SetRightText(footerlbl.Text).SetFontSize(6).SetFontName("Verdana");
            var pdf = pechkin.Convert(objConfig, receiptTemplate);

            var stream = new MemoryStream(pdf);
            result.Headers.AcceptRanges.Add("bytes");
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = string.Format("receipt_{0}_{1}.pdf", DateTime.Now.ToShortDateString(), receipt.IndexNumber);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            return result;
        }