public ActionResult DetallesAnalisisSuelo(int id)
        {
            Pdf pdf = new Pdf();

            pdf.generarPdf(id);
            return(View(analisisSuelo.getAnalisisSueloById(id)));
        }
Exemple #2
0
        public static void Create()
        {
            Pdf pdf = new Pdf();

            pdf.AddImage("images/cube.jpg", 100, 100, 40, 40);
            pdf.SaveFile(nameof(ImageExample));
        }
Exemple #3
0
        protected void CombineReports(List <string> files)
        {
            try
            {
                var guid     = Guid.NewGuid().ToString();
                var filename = guid + ".pdf";
                Session["CombinedReportPdf"] = ReportFrame.Src = "/Account/Receiving/" + filename;;
                var dest = Server.MapPath("/Account/Receiving/" + filename);
                if (files.Count == 0)
                {
                    return;
                }
                if (files.Count == 1)
                {
                    Pdf.Flatten(files[0], dest);
                    //File.Copy(files[0], dest);
                    ReportFrame.Src = "/Account/Receiving/" + filename;
                    return;
                }



                var result = Pdf.Merge(files, dest, true);
                if (result)
                {
                    ReportFrame.Src = "/Account/Receiving/" + filename;
                }
            }
            catch { }
        }
Exemple #4
0
        public bool CreateAndFill(string file, Dictionary <string, string> keys, StampAction action = null)
        {
            var temp = HttpContext.Current.Server.MapPath("/Account/PackingLists/" + Guid.NewGuid() + ".pdf");

            try
            {
                bool            result = false;
                Pdf.PackingSlip ps     = new Pdf.PackingSlip(Template);
                using (MemoryStream ms = new MemoryStream())
                {
                    if (action == null)
                    {
                        result = StampPdf(this.StampAction, temp, Template.TemplateBytes);
                    }
                    else
                    {
                        result = StampPdf(action, temp, Template.TemplateBytes);
                    }


                    if (result)
                    {
                        //fill data
                        using (MemoryStream fms = new MemoryStream())
                        {
                            result = Pdf.FillInForm(temp, file, keys);
                        }
                    }
                }
                File.Delete(temp);
                return(result);
            }
            catch { return(false); }
        }
Exemple #5
0
        public async Task <ActionResult> PostPdf()
        {
            var pdf   = (Pdf)null;
            var tuple = await ExtractFile();

            if (tuple.Item1 != null)
            {
                pdf = new Pdf
                {
                    Content    = tuple.Item1,
                    Size       = tuple.Item1.Length,
                    Title      = tuple.Item2,
                    UploadDate = DateTime.UtcNow
                };

                var  results = new List <ValidationResult>();
                bool isValid = Validator.TryValidateObject(pdf, new ValidationContext(pdf, null, null), results, true);

                if (isValid)
                {
                    await _pdfService.InsertPdf(pdf);

                    return(CreatedAtAction(nameof(GetPdf), new { id = pdf.Id }, pdf));
                }
            }

            return(BadRequest(ModelState));
        }
Exemple #6
0
        public ActionResult GetDeliveryPrint(int id, string reportName)
        {
            SalesDeliveryModel salesInvoiceModel = new SalesDeliveryModel();

            salesInvoiceModel = _iSalesDeliveryService.GetSalesDeliveryReportById(id);
            string html = _iSalesDeliveryService.GetDeliveryHtmlString(salesInvoiceModel, reportName);

            var pdf = Pdf
                      .From(html)
                      .OfSize(PaperSize.Letter)
                      .WithTitle("Title")
                      .WithoutOutline()
                      .WithMargins(.25.Centimeters())
                      .Portrait()
                      .Comressed()
                      .Content();

            string webRootPath = _hostingEnvironment.WebRootPath;
            string InvoicePath = Path.Combine(webRootPath, "Sales");
            string FileNmae    = InvoicePath + "\\SalesDelivery_" + DateTime.UtcNow.AddMinutes(LoginInfo.Timeoffset).ToString("MM/dd/yyyy HH:mm").Replace("/", "").Replace(" ", "").Replace(":", "").ToString() + ".pdf";

            Stream myStream = new MemoryStream(pdf);

            using (var fileStream = System.IO.File.Create(FileNmae))
            {
                myStream.Seek(0, SeekOrigin.Begin);
                myStream.CopyTo(fileStream);
            }

            byte[] FileBytes = System.IO.File.ReadAllBytes(FileNmae);
            return(File(FileBytes, "application/pdf"));
        }
Exemple #7
0
        public ActionResult FileUpload(HttpPostedFileBase pdf, string dosyaadı, string secilenders)
        {
            //  var Dersidbul = Database.Session.Query<Bolum_Ogretmen_Dersler>().FirstOrDefault(d => d.Kullanıcı_Numara.Numara == Convert.ToInt32(HttpContext.User.Identity.Name));
            // var dersidal = Database.Session.Query<Dersler>().FirstOrDefault(d => d.DersId == Dersidbul.DersID.DersId);

            bool iscontenttype(string ctype)
            {
                return(ctype.Equals("application/pdf"));
            }

            if (!iscontenttype(pdf.ContentType))
            {
                return(Content("UYUMSUZ DOSYA TİPİ. LÜTFEN PDF TİPİNDE BİR DOSYA GİRİNİZ"));
            }
            else
            {
                var filename = Path.GetFileName(pdf.FileName);
                var path     = Path.Combine(Server.MapPath("~/PDFfile"), filename);
                pdf.SaveAs(path);


                var pdffiles = new Pdf()
                {
                    Dosya_adı    = dosyaadı,
                    Dosya_konumu = path,
                    Ders_id      = Database.Session.Query <Dersler>().FirstOrDefault(d => d.DersAd == secilenders),
                    Ogretmen_id  = Database.Session.Load <Kisiler>(Convert.ToInt32(HttpContext.User.Identity.Name))
                };
                Database.Session.Save(pdffiles);
                Database.Session.Flush();

                return(RedirectToAction("Index", "Ogretmen"));
            }
        }
        public void GeneratePdf_ConverterShouldConvertToBytes()
        {
            // Arrange
            var concert = new Event
            {
                Artist = "Test",
                Time   = DateTime.Now
            };
            var tickets = new List <Ticket>
            {
                new Ticket
                {
                    CreatedAt = DateTime.Now,
                    Number    = "1"
                }
            };
            var pdfConverter     = new DummyPdfConverter();
            var barcodeConverter = new DummyBarcodeConverter();
            var httpClient       = new DummyHttpClient();

            // Act
            var pdf   = new Pdf(concert, tickets, pdfConverter, barcodeConverter, httpClient);
            var bytes = pdf.ToBytes();

            // Assert
            Assert.Single(bytes);
            Assert.Equal(0, bytes[0]);
        }
Exemple #9
0
        private void GenerateAndSendResults()
        {
            AssesmentReportTO report = new AssesmentReportTO();

            report.AssesmentInfo = info;
            report.Sections      = new List <SectionReportTO>();

            List <SectionPointsTO> list = AssesmentPersistence.GetAssesmentPoints(id);

            for (int i = 0; i < info.Evaluation.Sections.Count; i++)
            {
                SectionReportTO section = new SectionReportTO();
                section.Name       = info.Evaluation.Sections[i].Name;
                section.Percentage = 0;
                SectionPointsTO sectionPoints = list.Find(x => x.SectionID == info.Evaluation.Sections[i].ID);
                if (sectionPoints != null)
                {
                    section.Percentage = sectionPoints.Points;
                }

                report.Sections.Add(section);
            }

            report.Analysis = GetAnalysis();
            string savedFilePath = Pdf.GenerateSimplePdf(report);

            SendReport(savedFilePath);
        }
Exemple #10
0
 // GET: /PdfUpload/Delete/5
 public ActionResult Delete(int?id)
 {
     if (Session["username"] == null && Session["userid"] == null)
     {
         return(RedirectToAction("Index", "Home"));
     }
     try
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         Pdf pdf = db.Pdfs.Find(id);
         System.IO.File.Delete(pdf.PdfPath);
         if (pdf == null)
         {
             return(HttpNotFound());
         }
         return(View(pdf));
     }
     catch (Exception e)
     {
         ViewBag.Message = "File upload failed!!";
         return(View("Delete"));
     }
 }
Exemple #11
0
        public static void Create()
        {
            Pdf pdf = new Pdf();

            pdf.AddText("Hello World!", 10, 50);
            pdf.SaveFile(nameof(BasicExample));
        }
Exemple #12
0
        public void generatePDF()
        {
            var billBody = "";

            foreach (KeyValuePair <int, Item> keyValuePair in this.itemList)
            {
                var itemBody = "";
                this.BillAmount += keyValuePair.Value.amount;
                this.TotalItems += keyValuePair.Value.quantity;
                itemBody         = this.billBodyTemplate.Replace("@SrNo", keyValuePair.Key.ToString());
                itemBody         = itemBody.Replace("@Item", keyValuePair.Value.name.ToString());
                itemBody         = itemBody.Replace("@Price", keyValuePair.Value.price.ToString());
                itemBody         = itemBody.Replace("@Quantity", keyValuePair.Value.quantity.ToString());
                itemBody         = itemBody.Replace("@Amount", keyValuePair.Value.amount.ToString());
                billBody        += itemBody;
            }

            var    temp = basePath.ToString() + "/Templates/template.html";
            var    pdfs = basePath.ToString() + "/Pdfs/" + this.CustomerName.ToString() + this.BillDate.ToString("ddMMMyyyy") + ".pdf";
            string html = System.IO.File.ReadAllText(temp);

            html = html.Replace("@CustomerName", this.CustomerName.ToString());
            html = html.Replace("@CustomerMobile", this.CustomerMobile.ToString());
            html = html.Replace("@Date", this.BillDate.ToString("dd-MMM-yyyy"));
            html = html.Replace("@Amount", this.BillAmount.ToString());
            html = html.Replace("@TotalItems", this.TotalItems.ToString());
            html = html.Replace("@BillBody", billBody.ToString());
            var pdf = Pdf.From(html);

            byte[] content = pdf.Content();
            File.WriteAllBytes(pdfs, content);
        }
Exemple #13
0
 [Category("SkipOnTeamCity")]         // Failed to find expected file on Linux?
 public void CreateTest()
 {
     try
     {
         Pdf    target  = new Pdf(_tf.Copy("T1.xhtml"), _tf.Copy("T1.css"));
         string outName = _tf.Output("T1.pdf");
         File.Delete(_tf.Output("T1.pdf"));
         target.Create(outName);
         bool fileOutputCreated   = false;
         bool fileExpectedCreated = false;
         if (File.Exists(_tf.Output("T1.pdf")))
         {
             fileOutputCreated = true;
         }
         if (File.Exists(_tf.Expected("T1.pdf")))
         {
             fileExpectedCreated = true;
         }
         Assert.IsTrue(fileOutputCreated);
         Assert.IsTrue(fileExpectedCreated);
     }
     catch (Pdf.MISSINGPRINCE) // If Prince not installed, ignore test
     {
     }
 }
        public HttpResponseMessage GetCorreos([FromBody] string html, int para)
        {
            try
            {
                // Parametros2 param = db.Parametros2.FirstOrDefault();
                var             user     = db.Clientes.Where(a => a.CodCliente == para).FirstOrDefault();
                List <Object[]> adjuntos = new List <Object[]>();
                var             pdf      = Pdf.From(html).WithObjectSetting("web.defaultEncoding", "utf-8").Content();


                MemoryStream newStream = new MemoryStream(pdf);

                newStream.Flush();
                newStream.Position = 0;
                adjuntos.Add(new object[] { (Stream)newStream, "Factura_Proforma.pdf" });
                //  adjuntos.Add(new object[] { pdf, "Liquidacion.pdf" });
                bool respuesta = SendV2(user.Email, "*****@*****.**", "", WebConfigurationManager.AppSettings["UserName"], user.Nombre, "Factura Proforma", html, WebConfigurationManager.AppSettings["HostName"], int.Parse(WebConfigurationManager.AppSettings["Port"].ToString()), false, WebConfigurationManager.AppSettings["UserName"], WebConfigurationManager.AppSettings["Password"], adjuntos);

                return(Request.CreateResponse(HttpStatusCode.OK, respuesta));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Exemple #15
0
 /// <summary>
 /// Verifica cual formato está chequeado y guardará una lista de cartas según lo chequeado.
 /// </summary>
 public void SeleccionarFormatoCartas()
 {
     if (rdoXml.Checked)
     {
         saveFileDialog.Filter = FILTROXML;
         SerializadoraXml <List <Carta> > serializadoraCarta = new SerializadoraXml <List <Carta> >();
         if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName != "")
         {
             serializadoraCarta.Guardar(saveFileDialog.FileName, InformeCompras.cartasInforme);
         }
     }
     else if (rdoTxt.Checked)
     {
         saveFileDialog.Filter = FILTROTXT;
         SerializadoraTxt <Carta> serializadoraTexto = new SerializadoraTxt <Carta>();
         if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName != "")
         {
             serializadoraTexto.Guardar(saveFileDialog.FileName, InformeCompras.cartasInforme);
         }
     }
     else
     {
         saveFileDialog.Filter = FILTROPDF;
         Pdf <Carta> pdf = new Pdf <Carta>();
         if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName != "")
         {
             pdf.CrearPdf(saveFileDialog.FileName, InformeCompras.cartasInforme);
         }
     }
 }
Exemple #16
0
        private async Task PickFile()
        {
            Working = true;

            try
            {
                var dialog = new OpenFileDialog()
                {
                    Multiselect = false, DefaultExt = "*.pdf", Filter = "PDF Documents (.pdf)|*.pdf"
                };
                var result = dialog.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    FileLocation = dialog.FileName;

                    using (var pdf = new Pdf(FileLocation))
                    {
                        Text = await pdf.GetText();
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                MessageBox.Show("Something went wrong :(", "Errorz", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                Working = false;
            }
        }
Exemple #17
0
        internal void crcPdf(Action <DocumentCatalog> Given, Action <DocumentCatalog> When = null, Action <DocumentCatalog> Then = null)
        {
            DocumentCatalog pdfWriter = Pdf.CreateExpert();

            Given(pdfWriter);

            MemoryStream ms = new MemoryStream();

            pdfWriter.Save(ms);

            LogInDebug(ms);

            ms.Seek(0, SeekOrigin.Begin);
            DocumentCatalog pdfRead = Pdf.Load(ms);

            if (When != null)
            {
                When(pdfRead);
            }

            if (Then != null)
            {
                Then(pdfRead);
            }
        }
Exemple #18
0
        public static byte[] Variant1()
        {
            string inputFilename  = "cert-simple2.html";
            string outputFilename = "cert-simple2.pdf";

            string html = Encoding.UTF8.GetString(File.ReadAllBytes(inputFilename));

            //byte[] pdf = new SimplePechkin(new GlobalConfig()).Convert(html);


            var pdf = Pdf
                      .From(html)
                      .Content();

            //.OfSize(PaperSize.A4)
            //.WithTitle("Title")
            //.WithoutOutline()
            //.WithMargins(1.25.Centimeters())
            //.Portrait()
            //.Comressed()
            //.Content();

            //File.WriteAllBytes(outputFilename, pdf);

            //var p = new Process();

            //p.StartInfo = new ProcessStartInfo(Path.Combine(Directory.GetCurrentDirectory(), outputFilename))
            //{
            //    UseShellExecute = true
            //};

            //p.Start();

            return(pdf);
        }
Exemple #19
0
 public PrintPayroll(Payroll payroll)
 {
     Payroll  = payroll;
     Fullname = CreateFullname();
     ToPdf    = new PrintToPdf(Fullname);
     PdfFile  = new Pdf(Fullname);
 }
Exemple #20
0
        public ActionResult UploadFiles(HttpPostedFileBase[] files, Pdf filepdf)
        {
            //Ensure model state is valid
            if (ModelState.IsValid)
            {   //iterating through multiple file collection
                foreach (HttpPostedFileBase file in files)
                {
                    //Checking file is available to save.
                    if (file != null)
                    {
                        var InputFileName  = Path.GetFileName(file.FileName);
                        var ServerSavePath = Path.Combine(Server.MapPath("~/Areas/pariwarlagat/UploadedFiles/") + InputFileName);
                        //Save file to server folder
                        file.SaveAs(ServerSavePath);



                        db.Pdfs.Add(new Pdf
                        {
                            status = false,
                            File   = ServerSavePath
                        });
                        db.SaveChanges();

                        //assigning file uploaded status to ViewBag for showing message to user.
                        ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";
                    }
                }
            }
            return(View());
        }
Exemple #21
0
        public virtual void SendTickets(Event concert, List <Ticket> tickets, String email)
        {
            var pdf = new Pdf(concert, tickets, PdfConverter, BarcodeConverter, HttpClient);

            _log.LogInformation("Combined PDF with barcodes");
            EmailService.SendTicket(email, pdf);
        }
Exemple #22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            page = Pdf.GetPage(PageNumber);
            ScrollView.SetPDFPage(page);
        }
Exemple #23
0
        public async Task <byte[]> GetCertificateAsync(int courseId, string studentId)
        {
            var studentInCourse = await this.db.FindAsync <StudentCourse>(studentId, courseId);

            if (studentInCourse == null)
            {
                return(null);
            }

            var student = await this.db.Users.FirstOrDefaultAsync(u => u.Id == studentId);

            var course = await this.db.Courses.FirstOrDefaultAsync(c => c.Id == courseId);

            var certificateHtml = String.Format(GlobalConstants.Html,
                                                course.Name,
                                                course.StartDate.ToShortDateString(),
                                                course.EndDate.ToShortDateString(),
                                                student.Name,
                                                studentInCourse.Grade,
                                                await GetTrainerName(course.TrainerId),
                                                DateTime.UtcNow.ToShortDateString()
                                                );

            return(Pdf.From(certificateHtml).Content());
        }
Exemple #24
0
        public void on_open1_activate(object o, EventArgs args)
        {
            FileSelection fs = new FileSelection("Select a PDF file...");

            // TODO: This doesn't filter the file list...
            fs.Complete("*.pdf");
            fs.Run();
            fs.Hide();

            appbar1.Push("Opening document...");
            m_doc = new Pdf(fs.Filename);
            appbar1.Push(m_doc.PageCount + " page document");

            // Populate the pages list
            Gtk.ListStore model = new Gtk.ListStore(typeof(string));
            Gtk.TreeIter  iter  = new Gtk.TreeIter();
            Console.WriteLine("List has " + model.NColumns + " columns");
            for (int i = 0; i < m_doc.PageCount; i++)
            {
                iter = model.Append();
                GLib.Value v = new GLib.Value((i + 1).ToString());
                model.SetValue(iter, 0, v);
            }
            pages.Model = model;
            pages.Show();
        }
Exemple #25
0
        public async Task <ActionResult> Save(PoForm poForm)
        {
            if (poForm == null || poForm.Vendor == null || poForm.LineItems == null)
            {
                throw new InvalidDataException();
            }

            if (poForm.Id == 0)
            {
                SaveNewPoForm(poForm);
            }
            else
            {
                SaveEditedPoForm(poForm);
            }

            // Take the PO form and turn it into a PDF, then write it.
            var url = Url.Action("CompleteForm", "Home", new { id = poForm.Id }, protocol: Request.Url.Scheme);
            var pdf = TuesPechkinService.ConvertToPdf(TuesPechkin.Service.Uri.PrdApp01, url);

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

            await Pdf.WriteAsPdf(poForm.Id, pdf);

            return(RedirectToAction("Info/" + poForm.Id, "Home"));
        }
Exemple #26
0
        static void Main(string[] args)
        {
            //var basePath = AppDomain.CurrentDomain.BaseDirectory;

            var basePath = Environment.CurrentDirectory;

            var filesPath = Path.Combine(basePath, "Files");

            var pdfPath = Path.Combine(filesPath, "template.pdf");

            var htmlPath = Path.Combine(filesPath, "template.html");

            var html = File.ReadAllText(htmlPath);

            var pdf = Pdf
                      .From(html)
                      .OfSize(PaperSize.A4)
                      .WithTitle("PDF")
                      .WithoutOutline()
                      .WithMargins(1.Centimeters())
                      .Portrait()
                      .Comressed()
                      .Content();

            File.WriteAllBytes(pdfPath, pdf);
        }
Exemple #27
0
        public IHttpActionResult GetPdfData([FromBody] int MedicalResultId)
        {
            return(ApiResult <string>(() =>
            {
                var PersonIdRequester = ApplicationContext.Current.GetPersonIdUserAuthenticated();
                var html = this.CoreBusinessRules.GetPdfData(PersonIdRequester, MedicalResultId);

                string pdfdir = ConfigurationManager.AppSettings["pdfs"];
                var pdfPath = pdfdir + @"\" + Guid.NewGuid().ToString() + ".pdf";
                if (!File.Exists(pdfPath))
                {
                    if (!Directory.Exists(pdfdir))
                    {
                        Directory.CreateDirectory(pdfdir);
                    }

                    var pdf = Pdf.From(html)
                              .OfSize(PaperSize.A4)
                              .WithTitle("AC1 NOW - RESUMO DO EXAME")
                              .Content();


                    File.WriteAllBytes(pdfPath, pdf);
                }

                return html;
            }));
        }
        /// <summary>
        /// Ported from Profiling1.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="screeningEntity"></param>
        /// <param name="sortByRank"></param>
        /// <returns></returns>
        public byte[] GetExport(Request request, ScreeningEntity screeningEntity, bool sortByRank)
        {
            //sets the document information such as authors, etc.
            Pdf pdf = SetDocumentInformation();

            //landscape format
            pdf.IsLandscape = true;

            //creates the section that holds document content
            Section section = pdf.Sections.Add();

            //sets the header and footer for document
            section = SetHeaderFooter(request, section);

            //sets the title for document
            section = SetTitle(request, screeningEntity, section);

            //sets the request details
            section = SetRequestDetails(request, section);

            //sets the persons attached to the request
            section = SetPersonsAttached(request, screeningEntity, sortByRank, section);

            //creates the pdf in a byte array
            return(GetByteArray(pdf));
        }
Exemple #29
0
 public void CreatePdf()
 {
     var build     = new BuildSettings();
     Pdf pdf       = new Pdf(build.UrlPdf, build.Token);
     var xml       = GetXml(build);
     var pdfResult = pdf.GenerarPdf(xml, build.templateId, build.observaciones);
 }
Exemple #30
0
        public async Task SaveSiteRegistrationReview(int siteId, Pdf pdf)
        {
            var documentGuid = await _documentClient.SendFileAsync(new System.IO.MemoryStream(pdf.Data), pdf.Filename, $"sites/{siteId}/site_registration_reviews");

            _context.SiteRegistrationReviewDocuments.Add(new SiteRegistrationReviewDocument(siteId, documentGuid, pdf.Filename));
            await _context.SaveChangesAsync();
        }
Exemple #31
0
 public PdfPrinter(string path, Layout layout, Pdf.PdfFontSetting fontSetting)
 {
     Rectangle pdfPageSize;
     switch (layout.PageSize)
     {
         case PageSize.A5Portrait:
             pdfPageSize = iTextPageSize.A5;
             break;
         case PageSize.A4Landscape:
             pdfPageSize = iTextPageSize.A4.Rotate();
             break;
         default:
             throw new NotSupportedException();
     }
     _font = fontSetting.Font.CreateBaseFont(RunDirection.Vertical, false);
     _isPsuedoVertical = fontSetting.Font.PsuedoVertical;
     _headerFont = fontSetting.Font.CreateBaseFont(RunDirection.Horizontal, true);
     _latinFont = fontSetting.LatinFont.CreateBaseFont(RunDirection.Horizontal, true);
     _latinBaselineOffsetRatio = fontSetting.LatinBaselineOffsetRatio;
     _nombreFont = fontSetting.LatinFont.CreateBaseFont(RunDirection.Horizontal, true);
     _symbolFont = fontSetting.SymbolFont.CreateBaseFont(RunDirection.Vertical, false);
     _doc = new Document(pdfPageSize);
     _isMirrorEnabled = layout.Mirroring;
     _initialX = pdfPageSize.Width - layout.RightMargin - layout.FontSize / 2;
     _initialXMirrored = layout.RightMargin + layout.FontSize * 2 + layout.Leading * (layout.NumberOfLines - 2);
     _initialY = pdfPageSize.Height - layout.TopMargin;
     _pageX = pdfPageSize.Width - layout.PageNumberRightMargin;
     _pageY = pdfPageSize.Height - layout.PageNumberTopMargin;
     _pageFontSize = 10.5F;
     _pageHeaderOffset = layout.PageHeaderOffset;
     _writer = PdfWriter.GetInstance(_doc, new FileStream(path, FileMode.Create));
     _writer.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
     _writer.ViewerPreferences = PdfWriter.DirectionR2L | (layout.Mirroring ? PdfWriter.PageLayoutTwoPageRight : 0);
     _writer.SetFullCompression();
     _fontSizeChanged = true;
     _pageNumber = 0;
 }
Exemple #32
0
        private static void imageToPdf(Stream streamToConvert, Stream resultStream, ImageFileType imageFileType)
        {
            var pdfDocument = new Pdf();
            var pdfDocumentSection = pdfDocument.Sections.Add();

            var image = new Image(pdfDocumentSection)
            {
                ImageInfo =
                                    {
                                        ImageFileType = imageFileType,
                                        ImageStream = streamToConvert
                                    }
            };

            pdfDocumentSection.Paragraphs.Add(image);

            pdfDocument.Save(resultStream);
            streamToConvert.Close();
        }
Exemple #33
0
        public int enviarCorreoDeFactura(Usuario usuario, Compra compra)
        {
            try
            {
                MailMessage mensaje = new MailMessage();
                Pdf pdf = new Pdf();
                pdf.generar(usuario, compra);
                mensaje.To.Add(usuario.Email);
                mensaje.From = new MailAddress("*****@*****.**", "aei Store", System.Text.Encoding.UTF8);
                mensaje.Subject = "Notificación de procesamiento de factura";
                mensaje.IsBodyHtml = true;
                mensaje.Body = @"
                                    <img src = 'https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-ash4/381399_10201016661237859_441547910_n.jpg' />
                                    <h2>Estimado(a)" + usuario.Nombre + " " + usuario.Apellido + @",</h2>
                                    <p>
                                        Su pago en aei Store fue procesado. Le enviamos su factura electrónica, la cual le servirá para el recibo de su pedido. 
                                    </p>
                                    <h2>
                                        ¡Gracias por comprar en aei Store!
                                    </h2>
                                    <p>
                                      Si no reconoces haber realizado esta operación, o tienes cualquier duda, por favor escríbenos al correo electrónico [email protected].
                                    </p>";
                mensaje.Attachments.Add(new Attachment("C:/Factura" + compra.Id + ".pdf"));
                enviarCorreo(mensaje);
                return 1;
            }
            catch
            {
                return 0;
            }

        }       
Exemple #34
0
        public void Generate(string identifier)
        {
            try
            {
                Console.WriteLine($"Generate: Beginning generation for {Body}");
                MemoryStream ms = new MemoryStream();
                ms.Position = 0;

                Pdf pdf = new Pdf(ms);
                //var pdf = new Aspose.Pdf.Generator.Pdf();

                pdf.Author = "Benaissance";

                Section section = pdf.Sections.Add();

                section.Paragraphs.Add(new Aspose.Pdf.Generator.Text(Body));
                section.Paragraphs.Add(new Aspose.Pdf.Generator.Text("testing..."));
                //section.AddParagraph(new Text(Body));
                //section.AddParagraph(new Text("testing...."));
                //save it

                //name the blob

                string datePreFix = DateTime.Now.ToString("yyyyMMddhhmmss");

                string fname = $"notice_{identifier}_{datePreFix}_.PDF";

                Console.WriteLine("Closing PDF...");

                //pdf.Save(ms);

                pdf.Close();

                //TODO: change to keys
                //PasswordAuthenticationMethod pm = new PasswordAuthenticationMethod("preston", "<password here>");

                string noticesPath = string.Empty;

                if (Util.IsWindows())
                    noticesPath = Path.Combine( "c:\\local\\notices" , fname);
                else
                    noticesPath = Path.Combine( "/notices" , fname);

                Console.WriteLine($"file save full path: {noticesPath}");

                //if (File.Exists(localFile)) File.Delete(localFile);
                //pdf.Save(localFile);

                ms.Position = 0;

                if (useLocalStorage)
                {
                    using (FileStream fs = new FileStream(noticesPath, FileMode.CreateNew))
                    {
                        byte[] data = ms.ToArray();

                        fs.Write(data, 0, data.Length);

                        fs.Flush();
                    }
                }
                else
                {
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);

                    //string containerPath = "https://benaissancedev.blob.core.windows.net/notices";

                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                    CloudBlobContainer container = blobClient.GetContainerReference("notices");
                    CloudBlockBlob blob = container.GetBlockBlobReference(fname);

                    container.CreateIfNotExists();

                    blob.UploadFromStream(ms);

                }

                Console.WriteLine($"Uploaded pdf {fname}");

            }
            catch (Exception ex)
            {

                Console.WriteLine($"Exception!  message:{ex.Message}, stacktrace:{ex.StackTrace}, source:{ex.Source}");

            }
        }