Exemplo n.º 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();
 }
Exemplo n.º 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);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Constructs HTML to PDF converter instance from <code>GlobalConfig</code>.
        /// </summary>
        /// <param name="config">global configuration object</param>
        public SimplePechkin(GlobalConfig config)
        {
            if (_log.IsTraceEnabled)
                _log.Trace("T:" + Thread.CurrentThread.Name + " Creating SimplePechkin");

            _globalConfig = config;

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

            this.IsDisposed = false;
        }
Exemplo n.º 4
0
        public string Get()
        {
            var config = new GlobalConfig();
            config.SetMargins(0, 0, 100, 0);
            config.SetOutputDpi(300);
            config.SetPaperSize(PaperKind.A4);

            var converter = Factory.Create(config);
            var contents = File.ReadAllText(@"C:\Users\janand\Documents\GitHub\Invoicer\InvoicerHost\invoice.html");
            var pdfBytes = converter.Convert(contents);

            using (var writer = new BinaryWriter(new FileStream(@"C:\Users\janand\Documents\test.pdf", FileMode.Create)))
            {
                writer.Write(pdfBytes);
            }

            return "yeah!";
        }
Exemplo n.º 5
0
        public ActionResult Index()
        {
            var view = ViewEngines.Engines.FindView(ControllerContext, "index", null);
            FileContentResult actionResult;

            using (var writer = new StringWriter()) {
                var context = new ViewContext(ControllerContext, view.View, ViewData, TempData, writer);
                view.View.Render(context, writer);
                writer.Flush();
                var content = writer.ToString();

                var gc = new GlobalConfig();
                var converter = new SynchronizedPechkin(gc);
                var pdfbuf = converter.Convert(content);

                actionResult = File(pdfbuf, "application/pdf");
            }

            return actionResult;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Constructs HTML to PDF converter instance from <code>GlobalConfig</code>.
        /// </summary>
        /// <param name="config">global configuration object</param>
        public SimplePechkin(GlobalConfig config)
        {
            if (_log.IsTraceEnabled)
                _log.Trace("T:" + Thread.CurrentThread.Name + " Creating SimplePechkin");

            // create and STORE delegates to protect them from GC
            _errorCallback = OnError;
            _finishedCallback = OnFinished;
            _phaseChangedCallback = OnPhaseChanged;
            _progressChangedCallback = OnProgressChanged;
            _warningCallback = OnWarning;

            PechkinStatic.InitLib(false);

            _globalConfig = config;

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

            CreateConverter();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns an instance of a PDF converter that implements the IPechkin interface.
        /// </summary>
        /// <param name="config">A GlobalConfig object for the converter to apply.</param>
        /// <returns>IPechkin</returns>
        public static IPechkin Create(GlobalConfig config)
        {
            if (Factory.operatingDomain == null)
            {
                Factory.SetupAppDomain();
            }

            String location = Factory.realAssemblyLocation ?? Assembly.GetExecutingAssembly().Location;

            ObjectHandle handle = Activator.CreateInstanceFrom(
                Factory.operatingDomain,
                location,
                typeof(SimplePechkin).FullName,
                false,
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new object[] { config },
                null,
                null,
                null);

            IPechkin instance = handle.Unwrap() as IPechkin;

            Proxy proxy = new Proxy(instance, Factory.invocationDelegate);

            Factory.proxies.Add(proxy);

            proxy.Disposed += Factory.OnInstanceDisposed;

            return proxy;
        }
Exemplo n.º 8
-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);
        }
        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);
        }
Exemplo n.º 10
-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;
        }
Exemplo n.º 11
-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;
            }
        }