Пример #1
0
        public string writeHTMLtoPDF(string html, string pfad)
        {
            PdfDocument pdf1 = PdfGenerator.GeneratePdf(html, config);

            pfad = checkSlash(pfad);
            string alternativerPfad = pfad.Remove(pfad.Length - 5, 1);

            try
            {
                pdf1.Save(pfad);
                return(checkSlash(pfad));
            }
            catch (Exception ef)
            {
            }
            try
            {
                pdf1.Save(alternativerPfad);
                return(checkSlash(alternativerPfad));
            }

            catch (Exception e) {
            }


            return(pfad);
        }
Пример #2
0
        public static byte[] BuildTicketPdf(IEnumerable <PassengerForEditDto> passengers, Booking booking, FlightDetailsDto flight, User user)
        {
            var data = "<h2>Opole Airport reservation</h2>";

            data += $"Customer: {user.FirstName} {user.LastName}<br/>";
            data += $"Number of passengers: {booking.NumberOfPassengers}.<br/>";
            data += $"Flight from {flight.Origin.City}, " +
                    $"departure: {flight.DateOfDeparture:dddd, dd MMMM yyyy, HH:mm} UTC " +
                    $"to {flight.Destination.City}, " +
                    $"arrival: {flight.DateOfArrival:dddd, dd MMMM yyyy, HH:mm} UTC<br/>";
            data += $"Passengers for booking number {booking.Id}: <br/>";
            foreach (var passenger in passengers)
            {
                data += "<hr>";
                data += $"Name <b>{passenger.FirstName}</b>, Surname: <b>{passenger.LastName}</b>, " +
                        $"PESEL/Passport no.: <b>{passenger.IDNumber}</b> <br/>";
                data += $"Address: <b>{passenger.Street} {passenger.StreetNumber}</b>, City: <b>{passenger.City}</b>, " +
                        $"Post code: <b>{passenger.PostCode}</b>, Country: <b>{passenger.Country}</b><br/>";
            }

            using var ms = new MemoryStream();
            var pdf = PdfGenerator.GeneratePdf(data, PageSize.A4);

            pdf.Save(ms);
            return(ms.ToArray());
        }
Пример #3
0
 private void buttonExportPDF_Click(object sender, EventArgs e)
 {
     if (MessagesTreeView.Nodes.Count > 0)
     {
         saveFileDialogExport.FileName = "ExportedMessages" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm");
         if (saveFileDialogExport.ShowDialog() == DialogResult.OK)
         {
             var messages =
                 MessagesTreeView.Nodes
                 .OfType <TreeNode>()
                 .Select(
                     node => new EmailModel
             {
                 From       = node.Nodes["fromNode"] != null ? (node.Nodes["fromNode"].Tag.ToString()) : (string.Empty),
                 Subject    = node.Text,
                 Body       = node.Tag.ToString(),
                 ReceivedOn = node.Nodes["ReceivedOn"].Tag.ToString()
             })
                 .ToList();
             string errorMessage;
             if (!PdfGenerator.GeneratePdf(messages, saveFileDialogExport.FileName, out errorMessage))
             {
                 MessageBox.Show("Error in generating pdf:" + errorMessage);
             }
         }
     }
     else
     {
         MessageBox.Show("Please add some messages first");
     }
 }
Пример #4
0
        public async Task SaveCorrectDataWithValidProjectionIdAndUserId()
        {
            // Arrange
            var db = this.GetDatabase();

            const int    projectionId = 1;
            const string userId       = "TestUserId";

            var projection = new Projection
            {
                Id       = projectionId,
                Date     = DateTime.MaxValue,
                Visitors = new List <UserProjections>()
            };

            db.Add(projection);
            await db.SaveChangesAsync();

            var pdfGenerator  = new PdfGenerator();
            var cinemaService = new CinemaService(db, pdfGenerator);

            // Act
            var result = await cinemaService.BookTicket(projectionId, userId);

            var savedEntry = db.Find <UserProjections>(projectionId, userId);

            // Assert
            result
            .Should()
            .Be(true);

            savedEntry
            .Should()
            .NotBeNull();
        }
        public void GenerateTest()
        {
            using var destinationStream = new MemoryStream();
            var signPngBytes = File.ReadAllBytes(@"D:\Backup\My\sign.png");

            var date = DateTime.UtcNow;

            PdfGenerator.GenerateConfirmationOfServicesForm(
                destinationStream,
                signPngBytes,
                "ИП Стуков Константин Михайлович",
                "Stukov Konstantin Mihaylovich (Individual entrepreneur)",
                1278.14,
                date);

            var bytes = destinationStream.ToArray();
            var path  = Path.Combine(
                Path.GetTempPath(),
                $"Confirmation of Services Form - {date.ToString("MMMM dd, yyyy", CultureInfo.InvariantCulture)}.pdf");

            File.WriteAllBytes(path, bytes);

            Process.Start(new ProcessStartInfo("chrome.exe", $"\"{path}\"")
            {
                UseShellExecute = true,
            });
        }
Пример #6
0
        public void GeneratePdfBase64_Success()
        {
            // Arrange
            var html = @"
                <html>
                    <body>
                        <p>Test document</p>
                    </body>
                </html>
            ";

            // Act
            var result = string.Empty;

            using (var stream = new MemoryStream())
            {
                var pdf = PdfGenerator.GeneratePdf(html, PdfSharpCore.PageSize.A4);

                pdf.Save(stream);

                result = Convert.ToBase64String(stream.ToArray());
            }

            // Assert
            result.Should().NotBeNullOrEmpty();
        }
Пример #7
0
        public async Task <bool> Handle(GerarRelatorioAtaFinalHtmlParaPdfCommand request, CancellationToken cancellationToken)
        {
            List <string> paginasEmHtml = new List <string>();

            foreach (var modelPagina in request.Paginas)
            {
                string html = string.Empty;

                html = GerarHtmlRazor(modelPagina, request.NomeTemplate);

                html = html.Replace("logo.png", SmeConstants.LogoSme);

                paginasEmHtml.Add(html);
            }

            //TODO: FILA PARA RELATORIO SEM DADOS?
            if (paginasEmHtml.Any())
            {
                PdfGenerator pdfGenerator = new PdfGenerator(converter);

                var directory = AppDomain.CurrentDomain.BaseDirectory;
                SentrySdk.AddBreadcrumb($"Gerando PDF", $"Caminho geração : {directory}");

                pdfGenerator.ConvertToPdf(paginasEmHtml, directory, request.CodigoCorrelacao.ToString());

                SentrySdk.AddBreadcrumb($"Indo publicar na fila Prontos..", "8 - MonitorarStatusRelatorioUseCase");
                servicoFila.PublicaFila(new PublicaFilaDto(new MensagemRelatorioProntoDto(request.MensagemUsuario, string.Empty), RotasRabbit.RotaRelatoriosProntosSgp, RotasRabbit.ExchangeSgp, request.CodigoCorrelacao));
                SentrySdk.CaptureMessage("8 - MonitorarStatusRelatorioUseCase - Publicado na fila PRONTO OK!");
            }

            return(true);
        }
Пример #8
0
        public byte[] Generate()
        {
            var generator = new PdfGenerator();

            generator.AddCatalog(_catalog);
            generator.AddObject(_pages);

            foreach (var fontObject in _fonts.ToDictionary())
            {
                generator.AddObject(fontObject.Value);
                generator.AddObject(fontObject.Value.FontDescriptor);
                generator.AddObject(fontObject.Value.FontWidths);
            }

            foreach (var xObject in _xObjects.ToDictionary())
            {
                generator.AddObject(xObject.Value);
            }

            foreach (var pageObject in _pageObjects)
            {
                generator.AddObject(pageObject.Contents);
                generator.AddObject(pageObject);
            }

            return generator.GetBytes();
        }
Пример #9
0
        public int TestGen()
        {
            PdfDocument document = new PdfDocument();

            document.Info.Title = "Test Generation";

            PdfPage   page = document.AddPage();
            XGraphics gfx  = XGraphics.FromPdfPage(page);
            XFont     font = new XFont("Verdana", 20, XFontStyle.BoldItalic);

            // Draw the text
            gfx.DrawString("Hello, World!", font, XBrushes.Black,
                           new XRect(0, 0, page.Width, page.Height),
                           XStringFormats.Center);

            // Save the document...
            const string filename = "HelloWorld.pdf";
            string       test     = AppDomain.CurrentDomain.BaseDirectory;
            string       html     = System.IO.File.ReadAllText(test + "test.html");
            PdfDocument  htmltest = PdfGenerator.GeneratePdf(html, PageSize.Letter);

            htmltest.Save(test + filename);
            //// ...and start a viewer.
            //Process.Start(filename);
            return(1);
        }
Пример #10
0
        public void BarCodeGenerateTest()
        {
            var pdfGenerator = new PdfGenerator();

            pdfGenerator.BarCodeGenerate("0000000000-0000");
            Assert.IsTrue(true);
        }
Пример #11
0
        public static void Main(string[] args)
        {
            string currentDirectory    = Directory.GetCurrentDirectory();
            string phantomJsRootFolder = Path.Combine(currentDirectory, "PhantomJsRoot");

            // the pdf generator needs to know the path to the folder with .exe files.
            PdfGenerator generator = new PdfGenerator(phantomJsRootFolder);

            string htmlToConvert =
                @"
<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <h1>Hello World!</h1>
    <p>This PDF has been generated by PhantomJs ;)</p>
</body>
</html>
";
            // Generate pdf from html and place in the current folder.
            string pathOftheGeneratedPdf = generator.GeneratePdf(htmlToConvert, currentDirectory);

            Console.WriteLine("Pdf generated at: " + pathOftheGeneratedPdf);
        }
Пример #12
0
        public HttpResponseMessage ExportAsPDF()
        {
            // https://www.nuget.org/packages/HtmlRenderer.PdfSharp/
            // Install-Package HtmlRenderer.PdfSharp -Version 1.5.0.6

            var sDocument = @"
                <h1>Header<h1>
                <p>Content</p>
            ";

            var pdfDoc = PdfGenerator.GeneratePdf(sDocument, PageSize.A4);
            var stream = new MemoryStream();

            pdfDoc.Save(stream);
            ///pdfDoc.Save("D:\\1.pdf");

            var response = new HttpResponseMessage();

            response.Content = new ByteArrayContent(stream.ToArray());
            response.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = "export.pdf";
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            return(response);
        }
Пример #13
0
        public HttpResponseMessage CreatePdf(int projectId)
        {
            //add a draft thus this is not a published pdf
            bool draft = true;
            //there is no version, only projectId
            int versionId = 0;
            var project   = CoreFactory.ProjectRepository.GetProject(projectId);

            var creator = string.Empty;

            if (project.CreatedBy != null)
            {
                if (!string.IsNullOrEmpty(project.CreatedBy.Name))
                {
                    creator = project.CreatedBy.Name;
                }
            }

            PdfGenerator.GeneratePdf(project, creator, versionId, draft, projectRepository.GetRoles());

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ObjectContent <object>(new
                {
                    VersionId = versionId,
                    ProjectId = project.Id
                }, Configuration.Formatters.JsonFormatter)
            });
        }
Пример #14
0
        public GetController(
            MeritDbContext dbContext,
            InvoiceReportService invoiceReportService,
            AppSettings appSettings,
            InvoiceRepository invoiceRepository,
            InvoiceService invoiceService,
            LocationRepository locationRepository,
            WorkOrderRepository workOrderRepository,
            UnloadingWorkOrderQueries unloadingWorkOrderQueries,
            DlsWorkOrderQueries dlsWorkOrderQueries,
            BOLQueries bolQueries,
            ServiceWorkOrderQueries serviceWorkOrderQueries)
        {
            this.dbContext = dbContext;
            this.invoiceGenerationSettings = new InvoiceGenerationSettings();
            this.appSettings = appSettings;

            this.invoiceRepository   = invoiceRepository;
            this.locationRepository  = locationRepository;
            this.workOrderRepository = workOrderRepository;

            this.invoiceReportService = invoiceReportService;
            this.krogerExcelGenerator = new KrogerExcelGenerator(invoiceGenerationSettings.KrogerInvoiceTemplatePath);
            this.pdfGenerator         = new PdfGenerator();

            this.unloadingWorkOrderQueries = unloadingWorkOrderQueries;
            this.dlsWorkOrderQueries       = dlsWorkOrderQueries;
            this.invoiceService            = invoiceService;
            this.bolQueries = bolQueries;
            this.serviceWorkOrderQueries = serviceWorkOrderQueries;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void exportAsPDFMenuItem_Click(object sender, EventArgs e)
        {
            //Save!
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            //Default name of the file is the editor file name
            saveFileDialog.FileName = Path.GetFileNameWithoutExtension(this.FileInfo.FileName) + ".pdf";
            //The current path
            saveFileDialog.InitialDirectory = this.markdownViewer.Notepad.GetCurrentDirectory();
            //
            saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
            //
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                //Build a config based on made settings
                PdfGenerateConfig pdfConfig = new PdfGenerateConfig();
                pdfConfig.PageOrientation = this.markdownViewer.Options.pdfOrientation;
                pdfConfig.PageSize        = this.markdownViewer.Options.pdfPageSize;
                //Set margins
                int[] margins = this.markdownViewer.Options.GetMargins();
                pdfConfig.MarginLeft   = MilimiterToPoint(margins[0]);
                pdfConfig.MarginTop    = MilimiterToPoint(margins[1]);
                pdfConfig.MarginRight  = MilimiterToPoint(margins[2]);
                pdfConfig.MarginBottom = MilimiterToPoint(margins[3]);
                //Generate PDF and save
                PdfDocument pdf = PdfGenerator.GeneratePdf(BuildHtml(ConvertedText, this.FileInfo.FileName), pdfConfig, PdfGenerator.ParseStyleSheet(this.getCSS()));
                pdf.Save(saveFileDialog.FileName);

                //Open if requested
                if (this.markdownViewer.Options.pdfOpenExport)
                {
                    Process.Start(saveFileDialog.FileName);
                }
            }
        }
Пример #16
0
        public IHttpActionResult GetInvoicePdf(string orderNumber)
        {
            var searchCriteria = AbstractTypeFactory <CustomerOrderSearchCriteria> .TryCreateInstance();

            searchCriteria.Number = orderNumber;
            searchCriteria.Take   = 1;

            var order = _searchService.SearchCustomerOrders(searchCriteria).Results.FirstOrDefault();

            if (order == null)
            {
                throw new InvalidOperationException($"Cannot find order with number {orderNumber}");
            }

            var invoice = _notificationManager.GetNewNotification <InvoiceEmailNotification>(order.StoreId, "Store", order.LanguageCode);

            invoice.CustomerOrder = order;
            _notificationTemplateResolver.ResolveTemplate(invoice);

            var stream = new MemoryStream();
            var pdf    = PdfGenerator.GeneratePdf(invoice.Body, PdfSharp.PageSize.A4);

            pdf.Save(stream, false);
            stream.Seek(0, SeekOrigin.Begin);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            return(ResponseMessage(result));
        }
Пример #17
0
        /// <summary>
        /// Create PDF using PdfSharp project, save to file and open that file.
        /// </summary>
        private void OnGeneratePdf_Click(object sender, EventArgs e)
        {
            string outPDFPath = @"C:\Users\tmi\Downloads\obnova_kulturnych_pamiatok.1.0 (2)TMI (2).pdf";
            string htmlstring = generateHtml();

            if (!string.IsNullOrEmpty(htmlstring))
            {
                PdfGenerateConfig x = new PdfGenerateConfig();
                x.EnablePageNumbering        = true;
                x.PageNumbersFont            = new XFont("Times New Roman", 11);
                x.PageNumbersPattern         = "{0}/{1}";
                x.PageNumberLocation         = PageNumberLocation.Middle;
                x.PageNumbersMarginBottom    = 20;
                x.PageNumbersLeftRightMargin = 10;
                x.PageSize = PageSize.A4;
                x.SetMargins(30);
                var pdf = PdfGenerator.GeneratePdf(htmlstring, x, null, null, null);

                using (FileStream fs = new FileStream(outPDFPath, FileMode.Create))
                {
                    pdf.Save(fs, true);
                }

                System.Diagnostics.Process.Start(outPDFPath);
            }
        }
Пример #18
0
        public void CreatePdfReport(DateTime startDate, DateTime endDate, string pdfFullFileName, string cssFullFileName)
        {
            IList <SqlPdfFormat> data =
                SqlServerToPdf.GenerateSalesReport(sQLServerContext, startDate, endDate);

            PdfGenerator.GeneratePdf(data, pdfFullFileName, cssFullFileName);
        }
Пример #19
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            /*
             * PdfDocument document = new PdfDocument();
             *
             * PdfPage page = document.Pages.Add();
             *
             * PdfGraphics pdfGraphics = page.Graphics;
             *
             * PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14);
             *
             * pdfGraphics.DrawString("Testing!!", font, PdfBrushes.Black, new PointF(0,0));
             *
             * string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "./Pdf/DocTest.pdf");
             *
             * document.Save(filePath);
             */



            string      html = File.ReadAllText(path);
            PdfDocument pdf  = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);



            pdf.Save("document.pdf");

            string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "./document.pdf");

            Process.Start(filePath);
        }
Пример #20
0
        public static void Main(string[] args)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var generator        = new PdfGenerator();

            var htmlToConvert = @"
        <!DOCTYPE html>
        <html>
          <head>
          <style>
          /* Had to use this to fix the font sizing problem in linux. */
          html {
              height: 0;
              transform-origin: 0 0;
              -webkit-transform-origin: 0 0;
              transform: scale(0.53);
              -webkit-transform: scale(0.53);
          }
          </style>
          </head>
          <body>
              <h1>Hello World!</h1>
              <p>This PDF has been generated by PhantomJs ;)</p>
          </body>
        </html>";

            // Generate pdf from html and place in the current folder.
            var pathOfGeneratedPdf = generator.GeneratePdf(htmlToConvert, currentDirectory);

            Console.WriteLine("Pdf generated at: " + pathOfGeneratedPdf);
            Console.WriteLine("Press any key to close...");
            Console.ReadKey();
        }
        public static byte[] CreateLabels(IEnumerable <Expansion> expansionsToPrint)
        {
            var cardsToPrint = DominionCardDataAccess.GetCardsToPrint(expansionsToPrint);

            var trajan               = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Cinzel-Regular.ttf");
            var trajanBold           = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Cinzel-Bold.ttf");
            var baseFont             = BaseFont.CreateFont(trajan, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            var boldBaseFont         = BaseFont.CreateFont(trajanBold, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            var drawActionRectangles = cardsToPrint.SelectMany(card => new List <Action <PdfContentByte, Rectangle> >
            {
                (canvas, rectangle) =>
                {
                    var topCursor    = new Cursor();
                    var bottomCursor = new Cursor();
                    DrawBackgroundImage(card.SuperType, rectangle, canvas, topCursor, bottomCursor);
                    DrawCosts(boldBaseFont, card, rectangle, canvas, topCursor);
                    DrawSetImageAndReturnTop(rectangle, bottomCursor, card.Set.Image, canvas);

                    var cardName = card.GroupName ?? card.Name;
                    DrawCardText(rectangle, topCursor, bottomCursor, canvas, cardName, baseFont, card.SuperType);
                }
            }).ToList();
            var drawActionRectangleQueue = new Queue <Action <PdfContentByte, Rectangle> >(drawActionRectangles);

            return(PdfGenerator.DrawRectangles(drawActionRectangleQueue, BaseColor.WHITE));
        }
Пример #22
0
        public void PdfFinishTest()
        {
            var pdfGenerator = new PdfGenerator();
            var result       = pdfGenerator.PdfFinish();

            Assert.IsNull(result);
        }
Пример #23
0
        /// <summary>
        /// Generates a PDF report from the specified report XML document using the default XSLT file and returns
        ///   the file name of the generated PDF document
        /// The default XSLT file is FMO_PDFReport_Generic.xslt in RM.CommonLibrary.Reporting.Pdf
        /// The report XML document must be compliant with the schema defined in FMO_PDFReport_Generic.xsd in
        ///   RM.CommonLibrary.Reporting.Pdf. The RM.CommonLibrary.Reporting.Pdf.ReportFactoryHelper class
        ///   provides methods that create compliant elements and attributes, but the onus is on the developer
        ///   to verify that the report XML document is compliant
        /// </summary>
        /// <param name="reportXml">The XML report containing the report definition</param>
        /// <returns>The PDF document file name</returns>
        public string CreatePdfReport(string reportXml)
        {
            // Validate the arguments
            if (string.IsNullOrWhiteSpace(reportXml))
            {
                throw new ArgumentException($"{nameof(reportXml)} must not be null or empty.");
            }


            using (this.loggingHelper.RMTraceManager.StartTrace($"Business.{nameof(CreatePdfReport)}"))
            {
                string methodName = typeof(PDFGeneratorBusinessService) + "." + nameof(CreatePdfReport);
                this.loggingHelper.LogMethodEntry(methodName, LoggerTraceConstants.PDFGeneratorAPIPriority, LoggerTraceConstants.PDFGeneratorBusinessServiceMethodEntryEventId);


                // Create the PDF report with a new file name
                string pdfFileName = CreatePdfReportFileName();
                string pdfFilePath = Path.Combine(this.pdfReportFolderPath, pdfFileName);
                bool   created     = PdfGenerator.CreatePDF(reportXml, pdfFilePath);
                if (!created)
                {
                    pdfFileName = string.Empty;
                    pdfFilePath = string.Empty;
                }

                this.loggingHelper.LogMethodExit(methodName, LoggerTraceConstants.PDFGeneratorAPIPriority, LoggerTraceConstants.PDFGeneratorBusinessServiceMethodExitEventId);
                return(pdfFileName);
            }
        }
Пример #24
0
        public static byte[] CreateLabels(IEnumerable <Expansion> expansionsToPrint)
        {
            var cardsToPrint = DominionCardDataAccess.GetCardsToPrint(expansionsToPrint);

            var trajan               = Path.Combine(CurrentPath, "Fonts", "TRAJANPROREGULAR.TTF");
            var trajanBold           = Path.Combine(CurrentPath, "Fonts", "TRAJANPROBOLD.TTF");
            var font                 = PdfFontFactory.CreateFont(trajan, true);
            var boldFont             = PdfFontFactory.CreateFont(trajanBold, true);
            var drawActionRectangles = cardsToPrint.SelectMany(card => new List <Action <PdfCanvas, Rectangle> >
            {
                (canvas, rectangle) =>
                {
                    var topCursor    = new Cursor();
                    var bottomCursor = new Cursor();
                    topCursor.AdvanceCursor(rectangle.GetTop());
                    bottomCursor.AdvanceCursor(rectangle.GetBottom());
                    DrawBackgroundImage(card.SuperType, rectangle, canvas);
                    DrawCosts(boldFont, card, rectangle, canvas, topCursor);
                    DrawSetImageAndReturnTop(rectangle, bottomCursor, card.Set.Image, canvas);

                    var cardName = card.GroupName ?? card.Name;
                    DrawCardText(rectangle, topCursor, bottomCursor, canvas, cardName, font, card.SuperType);
                }
            }).ToList();
            var drawActionRectangleQueue = new Queue <Action <PdfCanvas, Rectangle> >(drawActionRectangles);

            return(PdfGenerator.DrawRectangles(drawActionRectangleQueue, ColorConstants.WHITE));
        }
Пример #25
0
        static void Main(string[] args)
        {
            var argsResult = new ApplicationArguments();

            argsResult.GetOptionSet().Parse(args);

            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.json", true, true)
                          .AddEnvironmentVariables();

            var config      = builder.Build();
            var pdfSettings = new PdfSettings();

            config.GetSection("PdfSettings").Bind(pdfSettings);
            try
            {
                using (var reader = File.OpenText(argsResult.InputFile))
                {
                    var html        = reader.ReadToEnd();
                    var pdfDocument = PdfGenerator.GeneratePdf(html, pdfSettings, null);
                    using (var writeStream = File.OpenWrite(argsResult.OutputFile))
                    {
                        using (var writer = new BinaryWriter(writeStream))
                        {
                            writer.Write(pdfDocument);
                        }
                    }
                }
                Console.WriteLine("Done!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #26
0
        public int CreateVersion(ProjectVersionModel projectVersion)
        {
            var version = new ProjectVersion();

            if (projectVersion != null)
            {
                version = ApplicationMapper.MapProjectVersion(projectVersion);
            }

            var project = new Project();

            if (projectVersion != null)
            {
                project = projectRepository.GetProject(projectVersion.ProjectId);
            }

            ISerializer xmlSerializer = new SerializeXml();

            xmlSerializer.Serialize(project);
            version.ProjectData = xmlSerializer.Serialize(project);

            int versionId = projectRepository.CreateVersion(version);

            //generate PDF
            PdfGenerator.GeneratePdf(project, projectVersion.PublishedByName, versionId, false, projectRepository.GetRoles());

            return(versionId);
        }
        public static void stampajUgovor()
        {
            PdfDocument pdf = PdfGenerator.GeneratePdf(
                @"<html>
                            <body style=""text-align:center;background-color:red"">
                                <p>
                                    <a href=""www.google.rs"">Hello World</a>
                                    This is html rendered text
                                </p>
                            </body>
                      </html>", PageSize.A4);

            pdf.Save("document.pdf");
            PrintDialog pDialog = new PrintDialog();

            pDialog.PageRangeSelection   = PageRangeSelection.AllPages;
            pDialog.UserPageRangeEnabled = true;

            // Display the dialog. This returns true if the user presses the Print button.
            bool?print = pDialog.ShowDialog();

            Aspose.Pdf.Document.Convert("document.pdf", null, "hello.xps", new XpsSaveOptions());
            if (print == true)
            {
                XpsDocument           xpsDocument = new XpsDocument("hello.xps", FileAccess.ReadWrite);
                FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
                pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job");
            }
        }
Пример #28
0
        static void Images()
        {
            IPdfGenerator generator = new PdfGenerator("Image tests", "Image tests", "Image tests", "Image tests");


            //System.IO.FileStream fs = new System.IO.FileStream(path: @"D:\DEVELOPMENT\GIT\OPTEN Solutions\tests\Opten.Web.Infrastructure.Pdf.Test\Images\reparaturloesungen.jpg", mode: System.IO.FileMode.Open, access: System.IO.FileAccess.Read);

            //generator.Elements.Add(new PdfImageFromStream(fs));
            generator.Elements.Add(new PdfHyperlink("http://www.opten.ch", MigraDoc.DocumentObjectModel.HyperlinkType.Web));
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            //generator.Elements.Add(new PdfImageFromStream(fs));
            //generator.Elements.Add(new PdfImageFromStream(fs));
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            generator.Elements.Add(new PdfImage(@"D:\DEVELOPMENT\GIT\OPTEN Solutions\tests\Opten.Web.Infrastructure.Pdf.Test\Images\reparaturloesungen.jpg", 215, 232));

            generator.Elements.Add(new PdfPageBreak());
            generator.Elements.Add(new PdfImage(@"D:\DEVELOPMENT\GIT\OPTEN Solutions\tests\Opten.Web.Infrastructure.Pdf.Test\Images\404.jpg", 1043, 792));
            generator.Elements.Add(new PdfImage(@"D:\DEVELOPMENT\GIT\OPTEN Solutions\tests\Opten.Web.Infrastructure.Pdf.Test\Images\404.jpg", 1043, 792));

            generator.Elements.Add(new PdfList(new TextLine[] { new TextLine("Hi"), new TextLine("Hi2"), new TextLine("hi3") }, PdfListType.OrderedList));
            generator.Elements.Add(new PdfList(new TextLine[] { new TextLine("Hi") }, PdfListType.UnorderedList));
            generator.Elements.Add(new PdfList(new TextLine[] { new TextLine("http://www.opten.ch"), new TextLine("http://www.opten.ch"), new TextLine("http://www.opten.ch") }, PdfListType.OrderedList, MigraDoc.DocumentObjectModel.HyperlinkType.Web));

            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            generator.Elements.Add(new PdfLineBreak());
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            generator.Elements.Add(new PdfParagraph(string.Empty));
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));
            generator.Elements.Add(new PdfParagraph("Ich bin ein text"));

            generator.SaveOnDisk(@"C:\Users\cfrei\Desktop\" + Guid.NewGuid() + ".pdf");
        }
Пример #29
0
        private byte[] ExportLetterToPdf(string html)
        {
            //recomend to use Pechkin.Synhrozine for generating pdf from html
            //recomend to use Pechkin.Synhrozine for generating pdf from html
            // byte[] bytes = new SimplePechkin(new GlobalConfig()).Convert(html);
            //IPechkin pechkin = new SynchronizedPechkin(new GlobalConfig());
            //byte[] bytes = pechkin.Convert(html);

            byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                var config = new PdfGenerateConfig();
                config.PageSize = PageSize.Letter;
                // config.PageSize = PageSize.A4;
                //todo: load margins from letter user settings for pdf
                config.MarginLeft   = 20;
                config.MarginRight  = 20;
                config.MarginTop    = 25;
                config.MarginBottom = 25;
                using (var pdf = PdfGenerator.GeneratePdf(html, config))
                {
                    if (pdf.PageCount == 0)
                    {
                        pdf.Close();
                        bytes = new byte[0];
                        return(bytes);
                    }
                    pdf.Save(ms, false);
                    bytes = ms.ToArray();
                }
            }
            return(bytes);
        }
        public IHttpActionResult GetInvoicePdf(string orderNumber)
        {
            var oderSearchResult = _searchService.SearchCustomerOrders(new CustomerOrderSearchCriteria
            {
                Number = orderNumber,
                Take   = 1
            });

            var order = oderSearchResult.Results.FirstOrDefault();

            if (order == null)
            {
                throw new NullReferenceException("order not found");
            }

            var invoice = _notificationManager.GetNewNotification(nameof(Invoice), null, null, "en-US");

            ((Invoice)invoice).Order = order;
            _notificationTemplateResolver.ResolveTemplate(invoice);

            var stream = new MemoryStream();
            var pdf    = PdfGenerator.GeneratePdf(invoice.Body, PdfSharp.PageSize.A4);

            pdf.Save(stream, false);
            stream.Seek(0, SeekOrigin.Begin);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            return(ResponseMessage(result));
        }
Пример #31
0
        public void TestMethod1()
        {
            byte by  = 201;
            var  zzz = new PdfGenerator().GetPdfByteStream("jhdjkhafk");

            Assert.AreEqual(by, zzz);
        }
Пример #32
0
        static void Main(string[] args)
        {
            PdfGenerator pdf = new PdfGenerator();

            PdfByte.ByteToPdfDisc(
                pdf.Generate(words[2], ImageByte.ImageToByteArray(images[0]), ImageByte.ImageToByteArray(images[1]),
                            ImageByte.ImageToByteArray(images[2]), ImageByte.ImageToByteArray(images[3])
                ), words[0], words[1]
            );

            Console.WriteLine(string.Format("Utworzono plik PDF.\nNazwa: {1}.pdf\nLokacja: {0}\nPelna sciezka: {0}{1}.pdf", words[0], words[1]));
            Console.ReadLine();
        }
        static void Main()
        {
            var sales = new List<SalesInfo>
            {
                new SalesInfo("Y50", 2700m, 5, "Lenovo"),
                new SalesInfo("Y50", 2700m, 5, "Lenovo"),
                new SalesInfo("Y50", 2700m, 5, "Lenovo"),
                new SalesInfo("Y50", 2700m, 5, "Lenovo"),
                new SalesInfo("Y50", 2700m, 5, "Lenovo"),
            };

            var pdfGenerator = new PdfGenerator(sales);
            pdfGenerator.SaveDocument(PdfReportsFolderPath, PdfReportsFileName);
        }
        /// <summary>
        /// It is imperative that the steps be executed in strict order, else errors and crashes may occur
        /// </summary>
        public static void Demo()
        {
            var data = new BoardgameSimulatorData(new BoardgameSimulatorDbContext());

            var mysql = new BoardgameSimulatorMySqlData();

            var mongoConnection = new MongoConnection();

            // Comment this line before starting the app, otherwise it will crash,
            // telling you that you have no rights to write into the MongoLab Db
            MongoDbDataSeeder.SeedToMongoDb(mongoConnection);

            // Feeds data from the MongoDb to SQL
            MongoDbDataSeeder.SeedToSql(mongoConnection, data);

            // Generates excel reports from which the db will later be seeded
            XlsReportGenerator.GenerateArmiesInExcel2003();

            // Feeds data from the excel reports into SQL
            ArmiesReportsSeeder.SeedArmies();

            // Feeds army vs army data from the MongoDb to SQL
            MongoDbDataSeeder.SeedBattleLogsToSql(mongoConnection, data);

            // Seeds the SqLiteDb with additional data about units
            SqLiteDataSeeder.Seed();

            // Additional data is exported from SQL into json files and into the MySQLDb
            JsonAndMySqlSeeder.Seed(mysql, data);

            var pdfGen = new PdfGenerator();
            pdfGen.CreatePerksGroupArmyReport(data.Armies.All());
            pdfGen.CreatePdfSkillsPotentialReport(data.Skills.All());

            var sqlite = new BoardgameSimulatorSqLiteData();

            var armyVs = mysql.ArmyVsArmyReports.All();
            var armyE = sqlite.UnitsCosts.All();

            new ExcelGenerator().CreateBattleLogExcelReport(armyVs, armyE);

            XmlImporter.ImportToSqlAndMongo(data, mongoConnection);

            new XmlGenerator().CreateHeroesReport(data.Heroes.All());
        }
        private void CreatePdf(Dictionary<int, IExerciseDefinition> exercises)
        {
            var pdfGen = new PdfGenerator(ConfigSettings.RootPath);

            pdfGen.InitializePage(DateTime.Now);

            for (var i = 0; i < 25; i++)
            {
                var currentEx = _randomNumberGenerator.GetRandomNumber(0, exercises.Count);
                try
                {
                    pdfGen.AddLine(string.Format("{0:00}. {1}", i + 1, exercises[currentEx].CreateExercise(_randomNumberGenerator)));
                }
                catch (Exception e)
                {
                    pdfGen.AddLine(string.Format("fout bij oefening {0}: {1}", exercises[currentEx].Name, e.Message));
                }
            }

            pdfGen.Write();
        }