Beispiel #1
0
        static void Main(string[] args)
        {
            MyPdfDocument pdfdoc = new MyPdfDocument();

            //1. create new page and append to doc
            MyPdfPage page = pdfdoc.CreatePage();

            pdfdoc.Pages.Add(page);
            //2. set page property
            MyPdfCanvas canvas = page.Canvas;

            canvas.DrawString("ABCD12345", 20, 20);
            //
            FonetDriver driver = FonetDriver.Make();

            driver.ImageHandler += str =>
            {
                return(null);
            };

            string outputFilename = "bin\\output.pdf";

            using (FileStream outputStream = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
            {
                driver.Render(pdfdoc, outputStream);
                outputStream.Flush();
                outputStream.Close();
            }
        }
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message.</param>
        /// <returns>Processed input message with appended or prepended data.</returns>
        /// <remarks>
        /// Converts xsl-fo transformed messages to pdf
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg)
        {
            IBaseMessagePart bodyPart = inmsg.BodyPart;

            if (bodyPart.Data != null)
            {
                VirtualStream vtstm = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);

                FonetDriver driver = FonetDriver.Make();
                driver.CloseOnExit = false;//important for biztalk to work ... set position = 0

                PdfRendererOptions options = new PdfRendererOptions();
                options.Title        = Title;
                options.Subject      = Subject;
                options.UserPassword = Password;

                driver.Options = options;

                Stream stm = bodyPart.GetOriginalDataStream();
                stm.Seek(0, SeekOrigin.Begin);

                driver.Render(stm, vtstm);

                vtstm.Seek(0, SeekOrigin.Begin);

                bodyPart.Data = vtstm;
            }
            return(inmsg);
        }
Beispiel #3
0
        private void convertXmlToPDF(string xmlFilename, bool preview = true)
        {
            string filename = Path.ChangeExtension(xmlFilename, ".pdf");

            var options = new PdfRendererOptions();

            options.Author         = Application.ProductName + " " + Application.ProductVersion;
            options.EnableModify   = false;
            options.EnableAdd      = false;
            options.EnableCopy     = false;
            options.EnablePrinting = true;
            FonetDriver driver = FonetDriver.Make();

            driver.Options = options;
            try
            {
                string s = doOpenDocument(xmlFilename, true);
                using (StringReader sr = new StringReader(s))
                {
                    using (FileStream fs = File.Create(filename))
                    {
                        driver.Render(sr, fs);
                    }
                }
                if (preview)
                {
                    Process.Start(filename);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            FonetDriver driver = FonetDriver.Make();

            driver.ImageHandler += str =>
            {
                return(null);
            };
            driver.Render("hello.fo", "hello.pdf");
        }
Beispiel #5
0
 protected void RenderPdf(XElement foDoc, String pdfFilename)
 {
     using (XmlReader xmlReader = foDoc.CreateReader())
         using (FileStream fileStream = File.Create(pdfFilename))
         {
             FonetDriver driver = FonetDriver.Make();
             driver.OnError += (o, args) =>
             {};
             driver.Render(xmlReader, fileStream);
         }
 }
        private static byte[] RenderFo2Pdf(string xmlFo)
        {
            var foReader = new XmlTextReader(new StringReader(xmlFo));

            var         options = new PdfRendererOptions();
            FonetDriver driver  = FonetDriver.Make();

            driver.OnError += HandleError;
            using (var stream = new MemoryStream())
            {
                driver.Options = options;
                driver.Render(foReader, stream);
                return(stream.ToArray());
            }
        }
Beispiel #7
0
        public void generar_pdf(XmlDocument fo, string rutaPDF)
        {
            FonetDriver driver  = FonetDriver.Make();
            var         options = new PdfRendererOptions();
            var         font    = new System.IO.FileInfo(@"c:/xml/arial.ttf");

            options.AddPrivateFont(font);
            options.FontType = FontType.Subset;
            driver.Options   = options;
            ///poner ruta pdf 417 que el nombre tiene que ser igual al tiempo de firma ej 2016-12-13T192207
            FileStream pdf_stream = null;

            pdf_stream = new FileStream(rutaPDF, FileMode.Create);
            driver.Render(fo, pdf_stream);
            //System.Diagnostics.Process.Start("c:/xml/hello.pdf");
        }
Beispiel #8
0
 static void Main(string[] args)
 {
     try
     {
         var myXslTrans = new XslCompiledTransform();
         myXslTrans.Load("stylesheet.xsl");
         myXslTrans.Transform("source.xml", "intermediate.fo");
         FonetDriver driver = FonetDriver.Make();
         driver.Render("intermediate.fo", "result.pdf");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
     Console.WriteLine("Press ENTER to exit");
     Console.ReadLine();
 }
Beispiel #9
0
        public void MakePdf(string rutaPDF)
        {
            FonetDriver driver = FonetDriver.Make();

            var options = new PdfRendererOptions();

            var font = new System.IO.FileInfo(@"C:\Windows\Fonts\arial.ttf");

            options.AddPrivateFont(font);

            options.FontType = FontType.Subset;

            driver.Options = options;

            FileStream PdfStream = null;

            PdfStream = new FileStream(rutaPDF, FileMode.Create);
            driver.Render(DTE, PdfStream);
        }
Beispiel #10
0
        protected void RenderPdf(XElement foDoc, String pdfFilename)
        {
            try
            {
                using (XmlReader xmlReader = foDoc.CreateReader())
                    using (FileStream fileStream = File.Create(pdfFilename))
                    {
                        FonetDriver driver = FonetDriver.Make();
                        //driver.OnError += (o, args) =>
                        //                {};

                        driver.Render(xmlReader, fileStream);
                    }
            }
            catch (Exception e)
            {
                Logger.WriteLine(e.ToString());
            }
        }
Beispiel #11
0
        /// <summary>
        /// Creates a PDF from an XSLFO representation of a report
        /// </summary>
        /// <param name="reportXslFo">String containing the XSLFO representation of the report</param>
        /// <param name="pdfFilePath">The full path to the output PDF file (existing file will be overwritten)</param>
        /// <returns>True if the PDF document was created successfully, otherwise false</returns>
        private static bool CreatePdfFromXslFo(string reportXslFo, string pdfFilePath)
        {
            // Validate the arguments
            if (string.IsNullOrWhiteSpace(reportXslFo))
            {
                throw new ArgumentException($"{nameof(reportXslFo)} must not be null or empty.");
            }
            if (string.IsNullOrWhiteSpace(pdfFilePath))
            {
                throw new ArgumentException($"{nameof(pdfFilePath)} must not be null or empty.");
            }


            // Load the report XSLFO document into an XML document
            XmlDocument xslfoDocument = new XmlDocument();

            xslfoDocument.LoadXml(reportXslFo);


            // Create a stream to write the PDF file into
            using (Stream pdfStream = new FileStream(pdfFilePath, FileMode.Create, FileAccess.Write))
            {
                // Set up the Fonet driver
                FonetDriver driver = FonetDriver.Make();

                // Configure the font options
                PdfRendererOptions options = new PdfRendererOptions();
                options.FontType = FontType.Link; // TODO or FontType.Embed or FontType.Subset
                                                  // options.AddPrivateFont(new FileInfo(@"\\server\fonts\rmgfont.otf"));
                driver.Options = options;

                // Create the PDF from the XSL-FO document
                driver.Render(xslfoDocument, pdfStream);
            }


            // Determine whether the PDF creation was successful
            bool success = File.Exists(pdfFilePath);

            return(success);
        }
Beispiel #12
0
        static void xslfoTest()
        {
            string root = @"C:\Users\Fernando.pires\Documents\Visual Studio 2015\Projects\PdfWriter\Files\Out\";

            if (File.Exists(root + "hello.pdf"))
            {
                File.Delete(root + "hello.pdf");
            }

            FileStream inStm = new FileStream(root + "{6F233C6B-3174-47FC-8A01-80A18DEBAD94}.xml", FileMode.Open);
            FileStream stm   = new FileStream(root + "hello.pdf", FileMode.Create);

            FonetDriver driver = FonetDriver.Make();
            //driver.CloseOnExit = false;//important for biztalk to work ... set position = 0

            PdfRendererOptions options = new PdfRendererOptions();

            driver.Render(inStm, stm);

            Console.ReadKey();
        }
        public void CreatePdf(Models.Card cardData, Stream outputStream)
        {
            if (cardData == null)
            {
                throw new ArgumentNullException("cardData");
            }

            if (outputStream == null)
            {
                throw new ArgumentNullException("outputStream");
            }

            var template = new Templates.ContactTemplate();

            template.Session         = new Dictionary <string, object>();
            template.Session["Data"] = cardData;
            template.Initialize();

            var foXmlString = template.TransformText();

            FonetDriver driver = FonetDriver.Make();

            driver.CloseOnExit = false;
            driver.Options     = new Fonet.Render.Pdf.PdfRendererOptions
            {
                Author         = "Mr. Smith",
                Title          = "How to create a PDF file using C#, T4 templates and Fo.Net.",
                Subject        = "Crazy stuff",
                EnableModify   = false,
                EnableAdd      = false,
                EnableCopy     = false,
                EnablePrinting = true,
                OwnerPassword  = "******",
            };

            using (var reader = new StringReader(foXmlString))
            {
                driver.Render(reader, outputStream);
            }
        }
Beispiel #14
0
        public static void generatePdf(MainWindowVM sender)
        {
            string testDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string xmlFilePath = Directory.GetParent(testDir).FullName + "\\Zad5\\toTransform.xml";
            string resultFOPath = Directory.GetParent(testDir).FullName + "\\Zad5\\Raport.fo";
            string resultFilePath = Directory.GetParent(testDir).FullName + "\\Zad5\\Raport.pdf";
            string transformFilePath = Directory.GetParent(testDir).FullName + "\\Zad5\\BookShopPDFTransform.xslt";

            sender.magazine.SerializeWithXSLT(xmlFilePath);

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(transformFilePath);
            transform.Transform(xmlFilePath, resultFOPath);
                        
            FonetDriver driver = FonetDriver.Make();
            try
            {
            driver.Render(resultFOPath, resultFilePath);
            } catch (Exception e)
            {
                MessageBox.Show("Sorry Error: " + e.Message);
            }

        }
Beispiel #15
0
        static void Main(string[] args)
        {
            FonetDriver driver = FonetDriver.Make();

            driver.Render("hello.fo", "hello.pdf");
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            bool throwException = Convert.ToBoolean(ConfigurationManager.AppSettings["ThrowExceptionOnSyntaxErrors"]);

            //var opts = new ExecutionOptions(args);
            var institutionalClaimToUb04ClaimFormTransformation = new InstitutionalClaimToUb04ClaimFormTransformation("UB04_Red.gif");
            var service = new ClaimFormTransformationService(
                new ProfessionalClaimToHcfa1500FormTransformation("HCFA1500_Red.gif"),
                institutionalClaimToUb04ClaimFormTransformation,
                new DentalClaimToJ400FormTransformation("ADAJ400_Red.gif"),
                new X12Parser(throwException));



            string filename   = @"E:\Projects\_temp\EdiFiles\EDI_INS_202009131900.edi";
            string OutputPath = @"E:\Projects\_temp\Output";
            bool   MakePdf    = true;

            try
            {
#if DEBUG
                var stream      = new FileStream(filename, FileMode.Open, FileAccess.Read);
                var parser      = new X12Parser();
                var interchange = parser.ParseMultiple(stream).First();
                File.WriteAllText(filename + ".dat", interchange.SerializeToX12(true));
                stream.Close();
#endif
                DateTime start           = DateTime.Now;
                var      inputFilestream = new FileStream(filename, FileMode.Open, FileAccess.Read);

                var revenueDictionary = new Dictionary <string, string>
                {
                    ["0572"] = "Test Code"
                };
                service.FillRevenueCodeDescriptionMapping(revenueDictionary);
                var claimDoc = service.Transform837ToClaimDocument(inputFilestream);
                institutionalClaimToUb04ClaimFormTransformation.PerPageTotalChargesView = true;
                var fi = new FileInfo(filename);
                var di = new DirectoryInfo(OutputPath);

                //if (opts.MakeXml)
                //{
                //    string outputFilename = $"{di.FullName}\\{fi.Name}.xml";
                //    string xml = claimDoc.Serialize();
                //    xml = xml.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\"");
                //    File.WriteAllText(outputFilename, xml);
                //}

                if (MakePdf)
                {
                    string outputFilename = $"{di.FullName}\\{fi.Name}.pdf";
                    using (FileStream pdfOutput = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
                    {
                        var    foDoc = new XmlDocument();
                        string foXml = service.TransformClaimDocumentToFoXml(claimDoc);
                        foDoc.LoadXml(foXml);

                        FonetDriver driver = FonetDriver.Make();
                        driver.Render(foDoc, pdfOutput);
                        pdfOutput.Close();
                    }
                }

                Console.WriteLine($"{filename} parsed in {DateTime.Now - start}.");
            }
            catch (Exception exc)
            {
                Console.WriteLine($"Exception occurred: {exc.GetType().FullName}.  {exc.Message}.  {exc.StackTrace}");
            }
            //    var stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
            //    var parser = new X12Parser();
            //    var interchange = parser.ParseMultiple(stream).First();
            //    File.WriteAllText(filename + ".dat", interchange.SerializeToX12(true));
            //    stream.Close();

            //}
            //private ClaimDocument Transform837ToClaimDocument(Stream stream)
            //{
            //    var parser = new X12Parser();
            //    var interchanges = parser.ParseMultiple(stream);
            //    var doc = new ClaimDocument();
            //    foreach (var interchange in interchanges)
            //    {
            //        var thisDoc = Transform837ToClaimDocument(interchange);
            //        this.AddRevenueCodeDescription(thisDoc);
            //        doc.Claims.AddRange(thisDoc.Claims);
            //    }

            //    return doc;
            //}
            Console.ReadLine();
        }
Beispiel #17
0
        /// <summary>
        /// Entry point into the command line interface.
        /// </summary>
        /// <param name="args">System provided command line arguments.</param>
        /// <returns>0 if successful, otherwise -1.</returns>
        internal int Run(string[] args)
        {
            try
            {
                long start = DateTime.Now.Ticks;

                CommandLineParser cmd = new CommandLineParser();
                this.fofOption      = cmd.AddParameterOption("fo");
                this.pdfOption      = cmd.AddOption("pdf");
                this.helpOption     = cmd.AddOption("h");
                this.kerningOption  = cmd.AddOption("kerning");
                this.fontTypeOption = cmd.AddParameterOption("fonttype");

                FonetDriver driver = FonetDriver.Make();
                driver.OnError += new FonetDriver.FonetEventHandler(this.FonetError);

                // May throw a CommandLineException if arguments are unparseable
                cmd.Parse(args);

                Stream inputStream  = null;
                Stream outputStream = null;

                if (this.helpOption.IsProvided)
                {
                    this.PrintUsage();
                    return(0);
                }

                if (this.fofOption.IsProvided)
                {
                    // The filename argument given to the -fo option
                    string fofFilename = this.fofOption.Argument;

                    try
                    {
                        // Attmept to open the source file
                        inputStream = new FileStream(
                            fofFilename, FileMode.Open, FileAccess.Read);
                    }
                    catch (Exception e)
                    {
                        throw new FonetException(
                                  String.Format("Unable to open file {0}", fofFilename), e);
                    }
                }
                else
                {
                    throw new FonetException("No input file specified");
                }

                driver.Options = this.GetPdfRendererOptions();

                string[] remainder = cmd.GetRemainder();
                if (remainder.Length > 0)
                {
                    string outputFile = remainder[0];
                    try
                    {
                        outputStream = new FileStream(outputFile, FileMode.Create);
                    }
                    catch (Exception e)
                    {
                        throw new FonetException(
                                  String.Format("Unable to open file {0}", outputFile), e);
                    }
                }
                else
                {
                    // Default to standard output
                    outputStream = Console.OpenStandardOutput();
                }

                driver.Render(inputStream, outputStream);

                long end = DateTime.Now.Ticks;

                Console.WriteLine("Took {0} ms.", (end - start) / 10000);
            }
            catch (CommandLineException cle)
            {
                Console.WriteLine("Incorrect commandline arguments: " + cle.Message);
                this.PrintUsage();
                return(-1);
            }
            catch (FonetException e)
            {
                Console.WriteLine("[ERROR] FO.NET failed to render your document: {0}", e.Message);
                return(-1);
            }
            catch (Exception e)
            {
                Console.WriteLine("[ERROR] {0}", e.Message);
                return(-1);
            }

            return(0);
        }
        internal static Stream Render(XDocument xXslFODoc, Stream outputStream, XslFORenderOptions options = null)
        {
            //Always use at least a Default set of options!
            //NOTE: The default constructor will initialize a default set of Options!
            var optionsToUse = options ?? new XslFORenderOptions();

            //Render the Binary PDF Output
            FonetDriver pdfDriver = XslFOFonetHelper.GetFonetDriver(optionsToUse.PdfOptions);
            Stopwatch   timer     = null;

            //Initialize Rendering Event Handlers if possible
            if (optionsToUse.RenderEventHandler != null)
            {
                timer = Stopwatch.StartNew();
                var fnFonetProxyEventHandler = new FonetDriver.FonetEventHandler((sender, eventArgs) => {
                    optionsToUse.RenderEventHandler(sender, new XslFOEventArg(eventArgs.GetMessage()));
                });

                pdfDriver.OnInfo    += fnFonetProxyEventHandler;
                pdfDriver.OnWarning += fnFonetProxyEventHandler;
            }

            //BBernard
            //Always ensure that at least a Default Error Event Handler is initialized to allow
            //  the Pdf's to render as much as possible despite many 'strict' errors that may occur.
            //NOTE: Because there may be numerous strict errors, but the report may still render acceptably,
            //      we always implement a Default Error Handler to allow reports to try their best to render
            //      to completion (when no other explicit error handler is specified by the consumer).
            pdfDriver.OnError += new FonetDriver.FonetEventHandler((sender, eventArgs) =>
            {
                Debug.WriteLine($"[XslFORenderer Error] {eventArgs.GetMessage()}");
            });

            //If any other Render Error Handlers are specified then we also attach it to Pdf Driver.
            if (optionsToUse?.RenderErrorHandler != null)
            {
                //BBernard
                //Create Lamda wrapper for the Fonet Event Handler to proxy into our Abstracted Event Handler
                //NOTE: This eliminates any dependencies on consuming code from the Fonet Driver
                pdfDriver.OnError += new FonetDriver.FonetEventHandler((sender, eventArgs) => {
                    var renderException = new XslFORenderException(eventArgs.GetMessage(), xXslFODoc?.ToString());
                    optionsToUse.RenderErrorHandler(sender, new XslFOErrorEventArg(renderException));
                });
            }
            else
            {
                //BBernard
                //If not Error Handler is defined then implement a default handler that ensures that
                //  an exception is thrown to provide fail-fast process as default behavior.
                //NOTE: This eliminates any dependencies on consuming code from the Fonet Driver
                pdfDriver.OnError += new FonetDriver.FonetEventHandler((sender, eventArgs) => {
                    throw new XslFORenderException(eventArgs.GetMessage(), xXslFODoc?.ToString());
                });
            }

            //Create the Xml Reader and then use the Pdf FONet Driver to output to the specified Stream
            using (XmlReader xmlFOReader = xXslFODoc.CreateReader())
            {
                //Render the Pdf Output to the defined File Stream
                pdfDriver.Render(xmlFOReader, outputStream);
            }

            //Reset the Stream if possible (since we return it ready to be possibly consumed/used...
            if (outputStream.CanSeek)
            {
                outputStream.Seek(0, SeekOrigin.Begin);
            }

            //Validate the rendered output
            if (!outputStream.CanRead || outputStream.Length <= 0)
            {
                throw new IOException("The rendered PDF output stream is empty; Xml FO rendering failed.");
            }

            //Log Benchmark event info if possible
            if (optionsToUse.RenderEventHandler != null && timer != null)
            {
                timer.Stop();
                optionsToUse.RenderEventHandler(null, new XslFOEventArg($"XslFO render to PDF execution completed in [{timer.Elapsed.TotalSeconds}] seconds"));
            }

            //Return the Output Stream for Chaining
            return(outputStream);
        }