コード例 #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            try
            {
                IronPdf.License.LicenseKey = "IRONPDF.DEVTEAM.IX3145-C34E80DCB2-ADJHRCSXUKPB-PKEVGHAWERN4-QR764J6FKUVF-C2SF2RA7BMOA-YFAVLMKNDRC5-7BDQGJ-LL4ZT5GOFJ2NEA-MINISTRYOFBUSINESS.IRO200810.4403.75155.ORG.5DEV.4YR-Q4SJ5M.RENEW.SUPPORT.10.AUG.2024";



                var pdf         = new IronPdf.PdfDocument("response.pdf");
                int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
                using (ByteArrayOutputStream memoryStream = new ByteArrayOutputStream(pdf.BinaryData.Length))
                {
                    using (MemoryStream inputStream = new MemoryStream(pdf.BinaryData))
                    {
                        iText.Kernel.Pdf.PdfDocument pdfDocument1 = new iText.Kernel.Pdf.PdfDocument(new PdfReader(inputStream), new PdfWriter(memoryStream));
                        pdfDocument1.Close();
                    }
                }
            }
            catch (Exception es)
            {
                var ass = es.Message;
            }
        }
コード例 #2
0
ファイル: PdfDocument.cs プロジェクト: ZayneLiu/Librarian
        protected override void Index()
        {
            var startTime = DateTime.Now;

            Console.Write($"Indexing {Name}");

            #region PDF
            // Get the PDF document from a `FileStream` via `PdfReader`.
            var pdfDocument =
                new Pdf.PdfDocument(new Pdf.PdfReader(new FileStream(Location, FileMode.Open, FileAccess.Read)));
            var totalPageNumber = pdfDocument.GetNumberOfPages();

            for (var i = 1; i <= totalPageNumber; i++)
            {
                // parser.ProcessPageContent(pdfDocument.GetPage(i+1));
                // var text = strategy.GetResultantText();
                var text = PdfTextExtractor.GetTextFromPage(pdfDocument.GetPage(i));

                this.AddToIndex(texts: text);
                // parser.Reset();
            }
            #endregion

            Console.Write($" >==> {Thumbnail.Count} unique words. {(DateTime.Now - startTime).TotalMilliseconds}ms\n");
        }
コード例 #3
0
        //////////////////////////////////////////////////////////
        //// public properties
        #region public properties

        /// <summary>
        /// Convert the Portable Document to text.
        /// </summary>
        /// <param name="file">The portable document file stream.</param>
        /// <param name="errors">Collection of errors that occur during reading the file stream.  Null if sucessful.</param>
        /// <returns>The text contents of the file.</returns>
        public static string Convert(Stream file, out List <Exception> errors)
        {
            StringBuilder result = new StringBuilder();

            errors = null;

            using (iText7.PdfReader reader = new iText7.PdfReader(file)) {
                using (iText7.PdfDocument doc = new iText7.PdfDocument(reader))
                {
                    int numberOfPages = doc.GetNumberOfPages();
                    for (int i = 1; i <= numberOfPages; i++)
                    {
                        try
                        {
                            var    page     = doc.GetPage(i);
                            string pagetext = iText7.Canvas.Parser.PdfTextExtractor.GetTextFromPage(page);
                            result.Append(Common.CleanPdfText(pagetext));
                        }
                        catch (Exception e)
                        {
                            if (errors == null)
                            {
                                errors = new List <Exception>();
                            }
                            errors.Add(e);
                        }
                    }
                }
            }

            return(result.ToString());
        }
コード例 #4
0
ファイル: Editor.xaml.cs プロジェクト: panchis7u7/Tutorias
        private async Task <string> pdfTextExtract(string sFilePath)
        {
            string texto;

            try
            {
                PdfReader reader = new PdfReader(sFilePath);
                iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(reader);
                texto = string.Empty;
                for (int page = 1; page <= pdf.GetNumberOfPages(); page++)
                {
                    ITextExtractionStrategy its = new SimpleTextExtractionStrategy();
                    String s = PdfTextExtractor.GetTextFromPage(pdf.GetPage(page), its);
                    //s = System.Text.Encoding.UTF8.GetString(ASCIIEncoding.Convert(System.Text.Encoding.Default, System.Text.Encoding.UTF8, System.Text.Encoding.Default.GetBytes(s)));
                    texto = texto + s;
                }
                reader.Close();
            }
            catch (Exception Ex)
            {
                await new MessageDialog("Error al abrir archivo: " + Ex.Message).ShowAsync();
                return(null);
            }
            return(texto);
        }
コード例 #5
0
        public static byte[] Combine(IEnumerable <byte[]> pdfs)
        {
            using (var writerMemoryStream = new MemoryStream())
            {
                using (var writer = new PdfWriter(writerMemoryStream))
                {
                    using (var mergedDocument = new iText.Kernel.Pdf.PdfDocument(writer))
                    {
                        var merger = new PdfMerger(mergedDocument);

                        foreach (var pdfBytes in pdfs)
                        {
                            using (var copyFromMemoryStream = new MemoryStream(pdfBytes))
                            {
                                using (var reader = new iText.Kernel.Pdf.PdfReader(copyFromMemoryStream))
                                {
                                    //have to set unethical reading to true else will get password error
                                    reader.SetUnethicalReading(true);
                                    using (var copyFromDocument = new iText.Kernel.Pdf.PdfDocument(reader))
                                    {
                                        //second parameter 1 is page number from where to start merge
                                        merger.Merge(copyFromDocument, 1, copyFromDocument.GetNumberOfPages());
                                    }
                                }
                            }
                        }
                    }
                }
                return(writerMemoryStream.ToArray());
            }
        }
コード例 #6
0
        private Document GeneratePDF(string use)
        {
            List <Bottles> listBottle = new List <Bottles>();

            //check which order by is selected, select the correct list depending on that
            if (radColor.Checked)
            {
                listBottle = Bottles.OrderByColor();
            }
            else if (radCountry.Checked)
            {
                listBottle = Bottles.OrderByCountry();
            }
            else if (radManufacturer.Checked)
            {
                listBottle = Bottles.OrderByManufacturer();
            }
            else if (radVariety.Checked)
            {
                listBottle = Bottles.OrderByVarietal();
            }
            else if (txtResearch.Text != "")
            {
                listBottle = Bottles.ResearchByKeyword(txtResearch.Text);
            }
            //if no ordering, select all bottles as they are in DB
            else
            {
                listBottle = Bottles.ShowAllBottles();
            }

            string jour = DateTime.Today.Day.ToString() + "." + DateTime.Today.Month.ToString() + "." + DateTime.Today.Year.ToString();
            // Must have write permissions to the path folder
            PdfWriter writer;

            if (use == "def")
            {
                writer = new PdfWriter("C:\\ListeBouteilles_" + jour + ".pdf");
            }
            else
            {
                writer = new PdfWriter("C:\\temp\\list" + jour + ".pdf");
            }
            //it is necessary to specify, because the class PdfDocument exist in both iText and Spire
            iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(writer);
            Document  document = new Document(pdf);
            Paragraph header   = new Paragraph("Liste de bouteilles stockées")
                                 .SetTextAlignment(TextAlignment.CENTER)
                                 .SetFontSize(14);

            document.Add(header);
            Table table = CreateTable(listBottle);

            document.Add(table);
            document.Close();

            return(document);
        }
コード例 #7
0
        private void SetFooter(PdfFormField toSet, iText.Kernel.Pdf.PdfDocument pdfDoc, int pagina, List <PdfConfiguratie> footerTeksten)
        {
            toSet.SetValue("");

            var afmetingen = toSet.GetWidgets().SelectMany(f => f.GetRectangle()).ToArray();
            var x          = (int)Convert.ToDouble(afmetingen[0].ToString().Replace(".", ","));
            var y          = (int)Convert.ToDouble(afmetingen[1].ToString().Replace(".", ","));
            var wWidth     = (int)Convert.ToDouble(afmetingen[2].ToString().Replace(".", ","));
            var wHeigth    = (int)Convert.ToDouble(afmetingen[3].ToString().Replace(".", ","));

            Document d           = new Document(pdfDoc);
            var      footerTekst = footerTeksten.FirstOrDefault();

            if (footerTekst == null)
            {
                return;
            }
            var paragraaf = new Paragraph(footerTekst.Value);

            paragraaf.SetFontSize(14);
            var styleBold = new Style();

            styleBold.SetBold();
            paragraaf.AddStyle(styleBold);
            var bottom = y + wHeigth - GetParagraafHeight(paragraaf, d, wWidth) * 2;

            paragraaf.SetFixedPosition(pagina, x, bottom, wWidth);
            d.Add(paragraaf);

            footerTekst = footerTeksten.Skip(1).FirstOrDefault();
            if (footerTekst == null)
            {
                return;
            }
            var paragraaf2 = new Paragraph(footerTekst.Value);

            paragraaf2.SetFontSize(12);
            bottom -= GetParagraafHeight(paragraaf2, d, wWidth);
            paragraaf2.SetFixedPosition(pagina, x, bottom, wWidth);
            d.Add(paragraaf2);

            footerTekst = footerTeksten.Skip(2).FirstOrDefault();
            if (footerTekst == null)
            {
                return;
            }
            var paragraaf3 = new Paragraph(footerTekst.Value);

            paragraaf3.SetFontSize(14);
            bottom -= GetParagraafHeight(paragraaf3, d, wWidth);
            paragraaf3.SetFixedPosition(pagina, x, bottom, wWidth);
            d.Add(paragraaf3);
        }
コード例 #8
0
        public PdfWriter(string fileName, Size pageSize, Rect drawingBounds)
        {
            double ymax = drawingBounds.Bottom;
            double ymin = drawingBounds.Top;
            double xmax = drawingBounds.Right;
            double xmin = drawingBounds.Left;

            m_scale = Math.Min(pageSize.Width / (xmax - xmin), pageSize.Height / (ymax - ymin));
            m_dx    = -xmin;
            m_dy    = -ymin;

            m_pdfDocument = new ITextPdf.PdfDocument(new iText.Kernel.Pdf.PdfWriter(fileName));
            m_canvas      = new ITextCanvas.PdfCanvas(m_pdfDocument.AddNewPage(new ITextGeom.PageSize((float)pageSize.Width, (float)pageSize.Height)));
        }
コード例 #9
0
        public static Document Document(bool horizontal = false)
        {
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new FileStream(PATH, FileMode.Create, FileAccess.Write)));

            if (horizontal)
            {
                pdfDocument.SetDefaultPageSize(pdfDocument.GetDefaultPageSize().Rotate());
            }

            Document doc = new Document(pdfDocument);

            doc.SetFont(FONT);
            return(doc);
        }
コード例 #10
0
        public static void AddPages()
        {
            PdfDocument pdfDocument = new PdfDocument(new PdfReader(PATH), new PdfWriter(new FileStream(PATH_PAGED, FileMode.Create, FileAccess.Write)));
            Document    doc         = new Document(pdfDocument);

            int numberOfPages = pdfDocument.GetNumberOfPages();
            var size          = pdfDocument.GetPage(1).GetPageSize();


            for (int i = 1; i <= numberOfPages; i++)
            {
                // Write aligned text to the specified by parameters point
                doc.ShowTextAligned(new Paragraph("Strona " + i + " z " + numberOfPages),
                                    size.GetWidth() - 50, 20, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
            }

            doc.Close();
        }
コード例 #11
0
ファイル: ReportPrinter.cs プロジェクト: amitdumka/eStore
        /// <summary>
        /// Add Page number at top of pdf file.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns> filename saved as</returns>
        public static string AddPageNumberToPdf(string fileName)
        {
            using PdfReader reader = new PdfReader(fileName);
            string fName = "cashBook_" + (DateTime.Now.ToFileTimeUtc() + 1001) + ".pdf";

            using PdfWriter writer = new PdfWriter(Path.Combine(ReportHeaderDetails.WWWroot, fName));

            using PdfDocument pdfDoc2 = new PdfDocument(reader, writer);
            Document doc2 = new Document(pdfDoc2);

            int numberOfPages = pdfDoc2.GetNumberOfPages();

            for (int i = 1; i <= numberOfPages; i++)
            {
                doc2.ShowTextAligned(new Paragraph("Page " + i + " of " + numberOfPages),
                                     559, 806, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
            }
            doc2.Close();
            return(fName);
        }
        public HttpResponseMessage DownloadMetaDataDocument(int ParentFolderId, int UserId)
        {
            HttpResponseMessage result = null;
            var dest = HttpContext.Current.Server.MapPath("~/Uploads/MetaDataDocument.pdf");

            if (File.Exists(dest))
            {
                File.Delete(dest);
            }
            var writer   = new PdfWriter(dest);
            var pdf      = new iText.Kernel.Pdf.PdfDocument(writer);
            var document = new Document(pdf);

            Queue <FolderDTO> folderDTOsQueue = new Queue <FolderDTO>();
            FolderDTO         folderDTO       = FolderBAL.GetFolderByFolderIdAndUserId(ParentFolderId, UserId);

            folderDTOsQueue.Enqueue(folderDTO);
            while (folderDTOsQueue.Count > 0)
            {
                folderDTO = folderDTOsQueue.Dequeue();
                document.Add(new Paragraph("Name: " + folderDTO.Name + "\nType: Folder\nSize: None\nParent: " + folderDTO.ParentFolderName));
                List <FilesDTO> fileDTOsList = FilesBAL.GetFilesByParentFolderIdAndUserId(folderDTO.Id, folderDTO.CreatedBy);
                foreach (FilesDTO fileDTO in fileDTOsList)
                {
                    document.Add(new Paragraph("Name: " + fileDTO.Name + "\nType: File\nSize: " + fileDTO.FileSizeInKB + " KB\nParent: " + folderDTO.ParentFolderName));
                }
                List <FolderDTO> folderDTOsList = FolderBAL.GetFoldersWithParentFolderNameByParentFolderIdAndUserId(folderDTO.Id, folderDTO.CreatedBy);
                foreach (FolderDTO tempDTO in folderDTOsList)
                {
                    folderDTOsQueue.Enqueue(tempDTO);
                }
            }
            document.Close();
            result         = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(new FileStream(dest, FileMode.Open, FileAccess.Read));
            result.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "MetaDataDocument.pdf";
            return(result);
        }
コード例 #13
0
ファイル: InformesServicio.cs プロジェクト: ander74/Orion
 /// <summary>
 /// Devuelve un PDF que se guardará en la ruta indicada, a partir de la plantilla necesaria para el tipo de informe indicado.
 /// </summary>
 /// <param name="ruta">Ruta completa (nombre de archivo incluido) en la que se guardará el PDF.</param>
 /// <param name="tipo">Tipo de informe que se va a generar.</param>
 /// <returns>El PDF listo para editar sus elementos.</returns>
 public iText.Kernel.Pdf.PdfDocument GetPdfDesdePlantilla(string ruta, TiposInforme tipo = TiposInforme.Ninguno)
 {
     // Definimos el pdf que se va a devolver.
     iText.Kernel.Pdf.PdfDocument docPdf = null;
     // Si hay un tipo de informe creamos el pdf.
     if (tipo != TiposInforme.Ninguno)
     {
         // Definimos la plantilla
         string plantilla = Utils.CombinarCarpetas(App.RutaInicial, $"/Plantillas/{tipo}.pdf");
         // Se crea el Reader con la plantilla necesaria.
         iText.Kernel.Pdf.PdfReader reader = new iText.Kernel.Pdf.PdfReader(plantilla);
         // Se crea el Writer con la ruta pasada.
         iText.Kernel.Pdf.PdfWriter writer = new iText.Kernel.Pdf.PdfWriter(ruta);
         // Creamos el documento, usando el reader y el writer anteriores.
         docPdf = new iText.Kernel.Pdf.PdfDocument(reader, writer);
         // Añadimos los datos de Metadata
         docPdf.GetDocumentInfo().SetAuthor("Orion - AnderSoft - A.Herrero");
         docPdf.GetDocumentInfo().SetCreator("Orion 1.0");
     }
     // Devolvemos el documento.
     return(docPdf);
 }
コード例 #14
0
        private void SetLogo(PdfFormField toSet, iText.Kernel.Pdf.PdfDocument pdfDoc, string filename, int pagina)
        {
            var b          = toSet as PdfButtonFormField;
            var afmetingen = b.GetWidgets().SelectMany(f => f.GetRectangle()).ToArray();
            var x          = (int)Convert.ToDouble(afmetingen[0].ToString().Replace(".", ","));

            if (x < 10)
            {
                x = 100;
            }
            var y         = (int)Convert.ToDouble(afmetingen[1].ToString().Replace(".", ","));
            var wWidth    = (int)Convert.ToDouble(afmetingen[2].ToString().Replace(".", ","));
            var pageWidth = (int)pdfDoc.GetPage(1).GetPageSizeWithRotation().GetWidth();

            if (wWidth > pageWidth - 20)
            {
                wWidth = pageWidth - 20;
            }
            var wHeight = (int)Convert.ToDouble(afmetingen[3].ToString().Replace(".", ","));

            if (pagina == 1)
            {
                wHeight -= 10;
            }

            ImageData img          = ImageDataFactory.Create(filename);
            var       pdfImage     = new iText.Layout.Element.Image(img);
            var       scaled       = pdfImage.ScaleToFit(wWidth, wHeight - y);
            var       scaledWidth  = scaled.GetImageScaledWidth();
            var       scaledHeight = scaled.GetImageScaledHeight();
            Document  d            = new Document(pdfDoc);

            var berekendeX = (x + wWidth - scaledWidth) / 2;
            var berekendeY = (y + wHeight - scaledHeight) / 2;

            scaled.SetFixedPosition(pagina, berekendeX, berekendeY);
            d.Add(scaled);
            b.SetValue("");
        }
コード例 #15
0
 public string GetTextFromPDF(string url)
 {
     try
     {
         StringBuilder ster = new StringBuilder();
         //DocumentModel document = DocumentModel.Load(url);
         PdfReader read = new PdfReader(url);
         iText.Kernel.Pdf.PdfDocument doc = new iText.Kernel.Pdf.PdfDocument(read);
         //foreach (var page in doc.GetPage(int page))
         for (int i = 0; i <= doc.GetNumberOfPages(); i++)
         {
             var word = ster.Append(PdfTextExtractor.GetTextFromPage(doc.GetPage(i)));
             text = word.ToString();
         }
         return(text);
     }
     catch (Exception)
     {
         text = "Error reading file";
         return(text);
     }
 }
コード例 #16
0
ファイル: InformesServicio.cs プロジェクト: ander74/Orion
 /// <summary>
 /// Devuelve un documento PDF nuevo en formato A5 en la ruta que se pasa como argumento.
 /// </summary>
 /// <param name="ruta">Ruta completa (nombre de archivo incluido) en la que se guardará el documento PDF.</param>
 /// <param name="apaisado">Si es true, el documento estará en apaisado. Por defecto es false.</param>
 /// <returns>El documento PDF listo para trabajar en él.</returns>
 public iText.Layout.Document GetNuevoPdfA5(string ruta, bool apaisado = false)
 {
     // Se crea el Writer con la ruta pasada.
     iText.Kernel.Pdf.PdfWriter writer = new iText.Kernel.Pdf.PdfWriter(ruta);
     // Se crea el PDF que se guardará usando el writer.
     iText.Kernel.Pdf.PdfDocument docPDF = new iText.Kernel.Pdf.PdfDocument(writer);
     // Añadimos los datos de Metadata
     docPDF.GetDocumentInfo().SetAuthor("Orion - AnderSoft - A.Herrero");
     docPDF.GetDocumentInfo().SetCreator("Orion 1.0");
     // Creamos el tamaño de página y le asignamos la rotaciñon si debe ser apaisado.
     iText.Kernel.Geom.PageSize tamañoPagina;
     if (apaisado)
     {
         tamañoPagina = iText.Kernel.Geom.PageSize.A5.Rotate();
     }
     else
     {
         tamañoPagina = iText.Kernel.Geom.PageSize.A5;
     }
     // Se crea el documento con el que se trabajará.
     iText.Layout.Document documento = new iText.Layout.Document(docPDF, tamañoPagina);
     return(documento);
 }
コード例 #17
0
        /// <summary>
        /// An enumeration of paragraphs of the portable document.
        /// </summary>
        /// <param name="file">The portable document file stream.</param>
        /// <returns>A <see cref="IEnumerable{T}"/> of paragraphs.</returns>
        public static IEnumerable <string> Paragraphs(Stream file)
        {
            using (iText7.PdfReader reader = new iText7.PdfReader(file))
            {
                using (iText7.PdfDocument doc = new iText7.PdfDocument(reader))
                {
                    int numberOfPages = doc.GetNumberOfPages();
                    for (int i = 1; i <= numberOfPages; i++)
                    {
                        iText7.PdfPage page     = doc.GetPage(i);
                        string         pagetext = iText7.Canvas.Parser.PdfTextExtractor.GetTextFromPage(page);
                        pagetext = Common.CleanPdfText(pagetext);

                        // Parse paragraphs.
                        IEnumerable <string> paragraphs = pagetext.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string item in paragraphs)
                        {
                            yield return(item);
                        }
                    }
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Sets the title.
        /// </summary>
        /// <param name="pdfFilePath">The PDF file path.</param>
        /// <param name="title">The title.</param>
        internal static void SetTitle(string pdfFilePath, string title)
        {
            if (string.IsNullOrEmpty(title))
            {
                return;
            }

            string tempFilePath = Path.GetTempFileName();

            using (PdfReader pdfReader = new PdfReader(pdfFilePath))
            {
                using (PdfWriter pdfWriter = new PdfWriter(tempFilePath))
                {
                    using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter))
                    {
                        PdfDocumentInfo pdfDocumentInfo = pdfDocument.GetDocumentInfo();
                        pdfDocumentInfo.SetTitle(title);
                    }
                }
            }

            File.Delete(pdfFilePath);
            File.Move(tempFilePath, pdfFilePath);
        }
コード例 #19
0
        /// <summary>
        /// Updates the links.
        /// </summary>
        /// <param name="pdfFilePath">The PDF file path.</param>
        /// <param name="htmlToPdfFiles">The HTML to PDF files.</param>
        /// <param name="logger">The logger.</param>
        internal static void UpdateLinks(
            string pdfFilePath,
            IReadOnlyCollection <HtmlToPdfFile> htmlToPdfFiles,
            ILogger logger)
        {
            string tempFilePath = Path.GetTempFileName();

            using (PdfReader pdfReader = new PdfReader(pdfFilePath))
            {
                using (PdfWriter pdfWriter = new PdfWriter(tempFilePath))
                {
                    using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter))
                    {
                        int pageCount = pdfDocument.GetNumberOfPages();
                        for (int i = 1; i <= pageCount; i++)
                        {
                            // get page
                            PdfPage pdfPage = pdfDocument.GetPage(i);

                            // get link annotations
                            IEnumerable <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>();
                            foreach (PdfLinkAnnotation linkAnnotation in linkAnnotations)
                            {
                                // get action
                                PdfDictionary action = linkAnnotation.GetAction();
                                if (action == null)
                                {
                                    continue;
                                }

                                PdfName s = action.GetAsName(PdfName.S);
                                if (s != PdfName.URI)
                                {
                                    continue;
                                }

                                PdfString uriPdfString = action.GetAsString(PdfName.URI);
                                if (!Uri.TryCreate(uriPdfString.GetValue(), UriKind.RelativeOrAbsolute, out Uri uri))
                                {
                                    continue;
                                }

                                if (!uri.IsFile)
                                {
                                    continue;
                                }

                                string htmlFilePath = uri.LocalPath.ToLower();

                                if (!htmlToPdfFiles.Any(x => string.Compare(x.Input, htmlFilePath, StringComparison.OrdinalIgnoreCase) == 0))
                                {
                                    // ex. when printing PDF from TOC.html by itself
                                    logger.LogDebug($"Could not find '{htmlFilePath}'. Referenced in '{pdfFilePath}' on page {i}.");
                                    continue;
                                }

                                HtmlToPdfFile linkedHtmlToPdfFile = htmlToPdfFiles.Single(x => x.Input == htmlFilePath);
                                int           linkedPageNumber    = linkedHtmlToPdfFile.OutputPdfFilePageNumber;

                                PdfPage linkedPage;
                                try
                                {
                                    // http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfDestination.html
                                    linkedPage = pdfDocument.GetPage(linkedPageNumber);
                                }
                                catch (Exception ex)
                                {
                                    throw new PdfPageNotFoundException(linkedPageNumber, linkedHtmlToPdfFile.Input, ex);
                                }

                                float top = linkedPage.GetPageSize().GetTop();
                                PdfExplicitDestination destination = PdfExplicitDestination.CreateFitH(linkedPage, top);
                                PdfAction newAction = PdfAction.CreateGoTo(destination);

                                linkAnnotation.SetAction(newAction);
                            }
                        }
                    }
                }
            }

            File.Delete(pdfFilePath);
            File.Move(tempFilePath, pdfFilePath);
        }
コード例 #20
0
        public ActionResult buildPDF(List <InformeResponse> lista, string nombreAsada)
        {
            MemoryStream ms = new MemoryStream();
            PdfWriter    pw = new PdfWriter(ms);

            PdfDocument pdfDocument = new PdfDocument(pw);
            Document    doc         = new Document(pdfDocument, PageSize.LETTER, false);

            doc.Add(new Paragraph("Reporte " + nombreAsada).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER).SetFontColor(new DeviceRgb(4, 124, 188)));
            foreach (InformeResponse item in lista)
            {
                Preguntas preguntasObj = TipoFormulario(item.tipo);

                doc.Add(new Paragraph(item.acueducto).SetFontSize(15).SetBold());
                doc.Add(new Paragraph("Fecha: " + item.fecha).SetFontSize(12));
                doc.Add(new Paragraph("Encargado: " + item.encargado).SetFontSize(12).SetPaddingBottom(2));
                doc.Add(new Paragraph("Respuestas ").SetFontSize(12).SetUnderline());

                var infra = JsonConvert.DeserializeObject <Dictionary <string, string> >(item.infraestructura);
                foreach (var kv in infra)
                {
                    if (kv.Key == "P1")
                    {
                        doc.Add(new Paragraph(preguntasObj.p1 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P2")
                    {
                        doc.Add(new Paragraph(preguntasObj.p2 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P3")
                    {
                        doc.Add(new Paragraph(preguntasObj.p3 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P4")
                    {
                        doc.Add(new Paragraph(preguntasObj.p4 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P5")
                    {
                        doc.Add(new Paragraph(preguntasObj.p5 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P6")
                    {
                        doc.Add(new Paragraph(preguntasObj.p6 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P7")
                    {
                        doc.Add(new Paragraph(preguntasObj.p7 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P8")
                    {
                        doc.Add(new Paragraph(preguntasObj.p8 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P9")
                    {
                        doc.Add(new Paragraph(preguntasObj.p9 + ": " + kv.Value).SetFontSize(10));
                    }
                }
                doc.Add(new Paragraph("Comentarios: " + item.comentarios).SetFontSize(12));
                doc.Add(new Paragraph("Tipo de formulario: " + preguntasObj.tipo).SetFontSize(12));
                Cell cell = new Cell();
                cell.Add(new Paragraph("Riesgo " + item.riesgo).SetBorder(new SolidBorder(colorRiesgo(item.riesgo), 1)).SetBackgroundColor(colorRiesgo(item.riesgo)).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetFontSize(14).SetBold());
                doc.Add(cell);

                WebClient webClient = new WebClient();
                byte[]    data      = webClient.DownloadData(item.imagen);

                ImageData imageData = ImageDataFactory.Create(data);
                Image     image     = new Image(imageData);
                var       s         = 0.4;
                float     fwi       = (float)s;
                float     fhei      = (float)s;
                doc.Add(image.Scale(fwi, fhei).SetHorizontalAlignment(HorizontalAlignment.CENTER).SetMarginBottom(15).SetMarginTop(15));
            }
            //imagen del logo de sersa
            var       s2         = 0.08;
            float     fwi2       = (float)s2;
            float     fhei2      = (float)s2;
            WebClient webClient2 = new WebClient();

            byte[]    data2      = webClient2.DownloadData(logoletra);
            ImageData imageData2 = ImageDataFactory.Create(data2);
            Image     image2     = new Image(imageData2);
            Paragraph header     = new Paragraph("");

            header.Add(image2.Scale(fwi2, fhei2).SetMarginBottom(15));


            //imagen del logo de TEC
            var       s3         = 0.4;
            float     fwi3       = (float)s3;
            float     fhei3      = (float)s3;
            WebClient webClient3 = new WebClient();

            byte[]    data3      = webClient3.DownloadData(logotec);
            ImageData imageData3 = ImageDataFactory.Create(data3);
            Image     image3     = new Image(imageData3);
            Paragraph header2    = new Paragraph("");

            header2.Add(image3.Scale(fwi3, fhei3)).SetMarginBottom(10);



            for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++)
            {
                Rectangle pageSize = pdfDocument.GetPage(i).GetPageSize();
                float     x1       = 20;
                float     y1       = pageSize.GetTop() - 55;
                float     x2       = pageSize.GetRight() - 30;
                float     y2       = pageSize.GetTop() - 40;
                doc.ShowTextAligned(header, x1, y1, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
                doc.ShowTextAligned(header2, x2, y2, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
            }



            doc.Close();

            byte[] bytesStream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(bytesStream, 0, bytesStream.Length);
            ms.Position = 0;

            return(new FileStreamResult(ms, "application/pdf"));
        }
コード例 #21
0
        public void CreatePdfDocument(int id, string userId)
        {
            var dbDoc = _db.CreatedPdfDocumenten
                        .Include(x => x.DocumentPartValues)
                        .Include(x => x.DocumentPartValues.Select(p => p.PdfDocumentPart))
                        .Include(x => x.PdfDocument)
                        .Include(x => x.UserInsert)
                        .Include(x => x.Logo)
                        .First(x => x.Id == id && x.UserInsert.Id == userId);

            var src         = Path.Combine(_basePathTemplates, dbDoc.PdfDocument.FileName);
            var destination = Path.Combine(_basePathUserSavedPdfs, dbDoc.UserInsert.Email, dbDoc.FileName);

            Directory.CreateDirectory(Path.GetDirectoryName(destination));

            iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(new PdfReader(src), new PdfWriter(destination));

            PdfAcroForm form              = PdfAcroForm.GetAcroForm(pdfDoc, true);
            var         fields            = form.GetFormFields();
            var         values            = dbDoc.DocumentPartValues.Select(x => new { x.Value, x.PdfDocumentPart.VeldNaam, x.PdfDocumentPart.Pagina });
            var         taalConfiguraties = _db.PdfConfiguraties.Where(x => x.Language == dbDoc.Taal).OrderBy(x => x.Key).ToList();

            foreach (var field in fields)
            {
                var          v = values.FirstOrDefault(va => va.VeldNaam == field.Key);
                PdfFormField toSet;
                fields.TryGetValue(field.Key, out toSet);

                // logo velden
                if (field.Key.ToLower().Contains("logo"))
                {
                    if (toSet is PdfButtonFormField)
                    {
                        SetLogo(toSet, pdfDoc, Path.Combine(_basePathTemplates, dbDoc.Logo.FileName), field.Key.ToLower() == "logo voorzijde" ? 1 : 2);
                    }
                    else
                    {
                        // zou niet mogen maar anders komt er een fout bij flattenfields
                        toSet.SetValue(field.Key);
                    }
                    continue;
                }

                // taalvelden
                if (field.Key.ToLower().Contains("footer") || field.Key.ToLower().Contains("afsluiting achterzijde"))
                {
                    SetFooter(toSet, pdfDoc, 2, taalConfiguraties);
                    continue;
                }

                // gewone velden
                if (v != null && v.Value != null)
                {
                    if (toSet is PdfButtonFormField)
                    {
                        var foto     = _db.Fotos.First(f => f.Id.ToString() == v.Value);
                        var filename = Path.Combine(_basePathFotos, foto.Path, foto.Name);

                        SetImage(toSet, pdfDoc, filename, v.Pagina);
                    }
                    else
                    {
                        // rekening houden met maxlen
                        var tekst = GetTekstBeperktOpMaxLen(toSet, v.Value);
                        toSet.SetValue(tekst);
                    }
                }
                else
                {
                    toSet.SetValue("");
                }
            }
            form.FlattenFields();
            pdfDoc.Close();

            //dbDoc.IsCreated = true;
            //_db.SaveChanges();
        }
コード例 #22
0
        //[EnableCors(origins: "*", headers: "*", methods: "*")]
        public ActionResult Novedadpdf(long numregistro, long tokenuserid)
        {
            try
            {
                string result = System.IO.Path.GetTempPath();
                Console.WriteLine(result);
                byte[] pdfBytes;

                MemoryStream stream = new MemoryStream(); //variable para crear en memoria el documento
                PdfWriter    writer = new PdfWriter(stream);
                //writer.SetCloseStream(true);
                iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(writer);
                Document document = new Document(pdf, PageSize.A4);
                document.SetMargins(110, 30, 30, 30);
                pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new ArchivosPDFNovedadEventHandler());

                //LETRAS
                //iText.IO.Font.FontProgram letra = iText.IO.Font.FontProgram.
                PdfFont letraNormal   = PdfFontFactory.CreateFont("Helvetica");
                PdfFont letraNegrilla = PdfFontFactory.CreateFont("Helvetica-Bold");

                //COLORES
                Color colorAprobado         = new DeviceRgb(237, 255, 237);
                Color colorRechazado        = new DeviceRgb(255, 237, 237);
                Color colorHeaderPrincipal  = new DeviceRgb(150, 150, 150);
                Color colorHeaderSecundario = new DeviceRgb(200, 200, 200);
                Color colorLetraEncabezado  = new DeviceRgb(255, 255, 255);
                Color colorLetraPrincipal   = new DeviceRgb(0, 0, 0);

                //Hora y Fecha
                Paragraph p = new Paragraph(string.Format("{0:dd/MM/yyyy hh:mm tt}, Bogotá D.C.", DateTime.Now))
                              .SetFont(letraNormal).SetFontSize(8).SetTextAlignment(TextAlignment.RIGHT);
                document.Add(p);

                //Titulo
                p = new Paragraph(string.Format("ACTA DE VALIDACIÓN - REPORTE NO ATENCIONES"))
                    .SetFont(letraNegrilla).SetFontSize(14).SetTextAlignment(TextAlignment.CENTER);
                document.Add(p);

                p = new Paragraph(string.Format("Apreciado prestador,\n"))
                    .SetFont(letraNormal).SetFontSize(10).SetTextAlignment(TextAlignment.JUSTIFIED);
                document.Add(p);

                p = new Paragraph(string.Format("{0}:", db.Web_Usuario.Where(u => u.usuario_id == tokenuserid).Select(x => string.Concat(x.razon_social.ToUpper())).FirstOrDefault()))
                    .SetFont(letraNegrilla).SetFontSize(10).SetTextAlignment(TextAlignment.JUSTIFIED);
                document.Add(p);
                //
                p = new Paragraph(string.Format("Se informa que su reporte de No Atenciones RIPS fue APROBADO con el número de registro {0} en la fecha {1} " +
                                                "A continuación se resumen los datos del prestador que reporto estas No Atenciones, así como la información general del registro:",
                                                numregistro, string.Format("{0:dd/MM/yyyy hh:mm tt}", db.Web_Novedad.Where(n => n.novedad_id == numregistro).Select(x => x.fecha_modificacion).FirstOrDefault())))
                    .SetFont(letraNormal).SetFontSize(10).SetTextAlignment(TextAlignment.JUSTIFIED);

                document.Add(p);

                //Tabla de información del prestador
                float[] anchoColumnas;

                anchoColumnas = new float[] { 3, 4 };
                Table tablaPrestador = new Table(UnitValue.CreatePercentArray(anchoColumnas)).SetWidth(UnitValue.CreatePercentValue(60)).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.CENTER);
                tablaPrestador.SetMarginTop(10);
                tablaPrestador.SetMarginBottom(10);

                Cell cell = new Cell(1, 2)
                            .Add(new Paragraph("Información del prestador:"))
                            .SetFont(letraNegrilla).SetFontSize(10).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)
                            .SetFontColor(colorLetraEncabezado).SetBackgroundColor(colorHeaderPrincipal, 0.9f)
                            .SetBorder(Border.NO_BORDER);
                tablaPrestador.AddHeaderCell(cell);
                // variable codigoprestador
                var codprestador = db.Web_Usuario.Where(u => u.usuario_id == tokenuserid).Select(x => x.Prestador.codigo).FirstOrDefault();
                tablaPrestador.AddCell(CrearCelda("key", "Código del prestador:"));
                tablaPrestador.AddCell(CrearCelda("value", string.Format("{0}", codprestador)));

                tablaPrestador.AddCell(CrearCelda("key", "Nombre del prestador:"));
                tablaPrestador.AddCell(CrearCelda("value", string.Format("{0}", db.Web_Usuario.Where(u => u.usuario_id == tokenuserid).Select(x => x.razon_social).FirstOrDefault())));

                tablaPrestador.AddCell(CrearCelda("key", "Email del prestador:"));
                tablaPrestador.AddCell(CrearCelda("value", string.Format("{0}", db.Web_Usuario.Where(u => u.usuario_id == tokenuserid).Select(x => x.correo).FirstOrDefault())));

                document.Add(tablaPrestador);

                //log.Warn(string.Format("se adiciono tabla del prestador"));

                //Tabla de información preradicacion
                anchoColumnas = new float[] { 4, 4 };
                Table tablaPrerradicacion = new Table(UnitValue.CreatePercentArray(anchoColumnas)).SetWidth(UnitValue.CreatePercentValue(100));

                cell = new Cell(1, 2)
                       .Add(new Paragraph("Información de Reporte:"))
                       .SetFont(letraNegrilla).SetFontSize(10).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)
                       .SetFontColor(colorLetraEncabezado).SetBackgroundColor(colorHeaderPrincipal, 0.9f)
                       .SetBorder(Border.NO_BORDER);

                tablaPrerradicacion.AddHeaderCell(cell);

                tablaPrerradicacion.AddCell(CrearCelda("key", "Fecha de inicio del reporte:"));
                tablaPrerradicacion.AddCell(CrearCelda("value", string.Format("{0:dd/MM/yyyy}", db.Web_Novedad.Where(n => n.novedad_id == numregistro).Select(x => x.periodofechainicio).FirstOrDefault())));

                tablaPrerradicacion.AddCell(CrearCelda("key", "Fecha de fin del reporte:"));
                tablaPrerradicacion.AddCell(CrearCelda("value", string.Format("{0:dd/MM/yyyy}", db.Web_Novedad.Where(n => n.novedad_id == numregistro).Select(x => x.periodofechafin).FirstOrDefault())));


                tablaPrerradicacion.AddCell(CrearCelda("key", "Usuarios:"));

                tablaPrerradicacion.AddCell(CrearCelda("value", string.Format("{0}", db.Web_Novedad.Where(u => u.FK_web_novedad_web_usuario == tokenuserid).Select(x => x.Web_Tipo_Novedad.nombre).FirstOrDefault())));

                //Tabla de información radicacion
                anchoColumnas = new float[] { 4, 4 };
                Table tablaRadicacion = new Table(UnitValue.CreatePercentArray(anchoColumnas)).SetWidth(UnitValue.CreatePercentValue(100));

                cell = new Cell(1, 2)
                       .Add(new Paragraph("Información de Acta:"))
                       .SetFont(letraNegrilla).SetFontSize(10).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)
                       .SetFontColor(colorLetraEncabezado).SetBackgroundColor(colorHeaderPrincipal, 0.9f)
                       .SetBorder(Border.NO_BORDER);

                tablaRadicacion.AddHeaderCell(cell);
                tablaRadicacion.AddCell(CrearCelda("key", "# REGISTRO:"));
                tablaRadicacion.AddCell(CrearCelda("value", string.Format("{0}", numregistro)));

                tablaRadicacion.AddCell(CrearCelda("key", "Fecha de radicación:"));
                tablaRadicacion.AddCell(CrearCelda("value", string.Format("{0:dd/MM/yyyy hh:mm tt}", db.Web_Novedad.Where(n => n.novedad_id == numregistro).Select(x => x.fecha_modificacion).FirstOrDefault())));


                //Insertar tablas de prerradicación y radicación
                anchoColumnas = new float[] { 10, 1, 10 };

                Table tablaInformacion = new Table(UnitValue.CreatePercentArray(anchoColumnas)).SetWidth(UnitValue.CreatePercentValue(100));
                tablaInformacion.SetMarginTop(10);
                tablaInformacion.SetMarginBottom(10);

                cell = new Cell()
                       .Add(tablaPrerradicacion)
                       .SetBorder(Border.NO_BORDER);
                tablaInformacion.AddCell(cell);

                tablaInformacion.AddCell(new Cell().SetBorder(Border.NO_BORDER));

                cell = new Cell()
                       .Add(tablaRadicacion)
                       .SetBorder(Border.NO_BORDER);
                tablaInformacion.AddCell(cell);

                document.Add(tablaInformacion);

                p = new Paragraph(string.Format("A continuación se indica el número de registros cargados para cada estructura:"))
                    .SetFont(letraNormal).SetFontSize(10).SetTextAlignment(TextAlignment.JUSTIFIED);
                document.Add(p);

                //Tabla de registros cargados
                anchoColumnas = new float[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
                Table tablaEstructuras = new Table(UnitValue.CreatePercentArray(anchoColumnas)).SetWidth(UnitValue.CreatePercentValue(100));
                tablaEstructuras.SetMarginTop(10);
                tablaEstructuras.SetMarginBottom(10);

                cell = new Cell(1, 9)
                       .Add(new Paragraph("Registros cargados por estructura"))
                       .SetFont(letraNegrilla).SetFontSize(10).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)
                       .SetFontColor(colorLetraEncabezado).SetBackgroundColor(colorHeaderPrincipal, 0.9f)
                       .SetBorder(Border.NO_BORDER);
                tablaEstructuras.AddHeaderCell(cell);

                //Header secundario
                foreach (var estructura in db.Estructura)
                {
                    cell = new Cell()
                           .Add(new Paragraph(estructura.acronimo))
                           .SetFont(letraNegrilla).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)
                           .SetFontColor(colorLetraPrincipal).SetBackgroundColor(colorHeaderSecundario, 0.9f)
                           .SetBorder(Border.NO_BORDER);
                    tablaEstructuras.AddHeaderCell(cell);
                }

                DataTable facturas = null;

                //Cantidad de registros
                foreach (var estructura in db.Estructura)
                {
                    int cantidad = 0;
                    tablaEstructuras.AddCell(CrearCelda("value", cantidad.ToString()));
                }
                document.Add(tablaEstructuras);

                p = new Paragraph(string.Format("Secretaría Distrital de Salud de Bogotá - Dirección de Planeación Sectorial \nPor favor conserve sus archivos en caso de ser requeridos por la entidad"))
                    .SetFont(letraNormal).SetFontSize(10).SetTextAlignment(TextAlignment.CENTER);
                document.Add(p);

                document.Close();
                pdfBytes = stream.ToArray();

                return(File(pdfBytes, "application/pdf", String.Concat("NoAtencion-Rad", numregistro, "_", string.Format("{0}", codprestador), ".pdf")));
            }
            catch (Exception e)
            {
                LogsController log = new LogsController(e.ToString());
                log.createFolder();
                //Envio mensaje de Error a la Vista
                throw new HttpException(404, "HTTP/1.1 404 Not Found");
            }
        }
コード例 #23
0
ファイル: HistorialModel.cs プロジェクト: dereck05/SERSA
        public ActionResult buildPDF(List <InformeResponse> lista, string nombreAsada)
        {
            MemoryStream ms = new MemoryStream();
            PdfWriter    pw = new PdfWriter(ms);

            PdfDocument pdfDocument = new PdfDocument(pw);
            Document    doc         = new Document(pdfDocument, PageSize.LETTER);

            doc.Add(new Paragraph("Reporte " + nombreAsada).SetFontSize(20).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetFontColor(new DeviceRgb(4, 124, 188)));
            foreach (InformeResponse item in lista)
            {
                Preguntas preguntasObj = TipoFormulario(item.tipo);

                doc.Add(new Paragraph(item.acueducto).SetFontSize(15).SetBold());
                doc.Add(new Paragraph("Fecha: " + item.fecha).SetFontSize(12));
                doc.Add(new Paragraph("Encargado: " + item.encargado).SetFontSize(12).SetPaddingBottom(2));
                doc.Add(new Paragraph("Respuestas ").SetFontSize(12).SetUnderline());

                var infra = JsonConvert.DeserializeObject <Dictionary <string, string> >(item.infraestructura);
                foreach (var kv in infra)
                {
                    if (kv.Key == "P1")
                    {
                        doc.Add(new Paragraph(preguntasObj.p1 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P2")
                    {
                        doc.Add(new Paragraph(preguntasObj.p2 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P3")
                    {
                        doc.Add(new Paragraph(preguntasObj.p3 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P4")
                    {
                        doc.Add(new Paragraph(preguntasObj.p4 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P5")
                    {
                        doc.Add(new Paragraph(preguntasObj.p5 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P6")
                    {
                        doc.Add(new Paragraph(preguntasObj.p6 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P7")
                    {
                        doc.Add(new Paragraph(preguntasObj.p7 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P8")
                    {
                        doc.Add(new Paragraph(preguntasObj.p8 + ": " + kv.Value).SetFontSize(8));
                    }
                    else if (kv.Key == "P9")
                    {
                        doc.Add(new Paragraph(preguntasObj.p9 + ": " + kv.Value).SetFontSize(8));
                    }
                }
                doc.Add(new Paragraph("Comentarios: " + item.comentarios).SetFontSize(12));
                doc.Add(new Paragraph("Tipo de formulario: " + preguntasObj.tipo).SetFontSize(12));
                Cell cell = new Cell();
                cell.Add(new Paragraph("Riesgo " + item.riesgo).SetBorder(new SolidBorder(colorRiesgo(item.riesgo), 1)).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetFontSize(14));
                doc.Add(cell);
            }

            doc.Close();

            byte[] bytesStream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(bytesStream, 0, bytesStream.Length);
            ms.Position = 0;

            return(new FileStreamResult(ms, "application/pdf"));
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: QuangBui3101/ManagingBooks
        static void Main(string[] args)
        {
            SQLiteConnection connection = new SQLiteConnection();

            SQLiteConnection.CreateFile("Data.sqlite");
            string script = File.ReadAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "Database1.sql"));

            connection = new SQLiteConnection(new SQLiteConnectionStringBuilder {
                DataSource = "Data.sqlite"
            }.ToString());
            connection.Open();
            var createDB = connection.CreateCommand();

            createDB.CommandText = script;
            createDB.ExecuteNonQuery();
            connection.Close();
            connection.Open();
            var insertCommand = connection.CreateCommand();

            insertCommand.CommandText = "INSERT INTO Books (Number, Title, Publisher, Version, Year, Medium, Place, DayBought, Pages, Price) " +
                                        "VALUES (@Number,@Title,@Publisher,@Version,@Year,@Medium,@Place,@Date,@Pages,@Price)";
            insertCommand.Parameters.AddWithValue("Number", 123);
            insertCommand.Parameters.AddWithValue("Title", "qwerqwr'");
            insertCommand.Parameters.AddWithValue("Publisher", "pub");
            insertCommand.Parameters.AddWithValue("Version", 1);
            insertCommand.Parameters.AddWithValue("Year", 2010);
            insertCommand.Parameters.AddWithValue("Medium", "med");
            insertCommand.Parameters.AddWithValue("Place", "bla");
            insertCommand.Parameters.AddWithValue("Date", "12122010");
            insertCommand.Parameters.AddWithValue("Pages", 15);
            insertCommand.Parameters.AddWithValue("Price", 15.2);
            insertCommand.ExecuteNonQuery();
            connection.Close();


            //using (PdfWriter pdfWriter = new PdfWriter(exportFile))
            //{
            //    using (iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(pdfWriter))
            //    {
            //        Rectangle envelope = new Rectangle(3016, 1327);
            //        PageSize ps = new PageSize(envelope);
            //        //ps.ApplyMargins(0, 0, 0, 0, true);
            //        Document document = new Document(pdf, ps);
            //        document.SetMargins(0, 0, 0, 0);
            //        Paragraph text = new Paragraph("Signature").SetTextAlignment(TextAlignment.CENTER).SetFontSize(200);
            //        Paragraph num = new Paragraph("011120").SetTextAlignment(TextAlignment.CENTER).SetFontSize(200);
            //        Barcode128 barcode128 = new Barcode128(pdf);
            //        barcode128.SetCodeType(Barcode128.CODE_C);
            //        barcode128.SetCode("011120");
            //        barcode128.FitWidth(2800);
            //        barcode128.SetBarHeight(700);
            //        barcode128.SetAltText("");

            //        Image barcodeImage = new Image(barcode128.CreateFormXObject(pdf));
            //        barcodeImage.SetHorizontalAlignment(HorizontalAlignment.CENTER);
            //        document.Add(text);
            //        document.Add(barcodeImage);
            //        document.Add(num);
            //    }
            //}
            //Spire.Pdf.PdfDocument document1 = new Spire.Pdf.PdfDocument();
            //document1.LoadFromFile(exportFile);
            //System.Drawing.Image img = document1.SaveAsImage(0);
            //img.Save(exportImage);
            //document1.SaveToFile(System.IO.Path.Combine(exportFolder, "bc.svg"), FileFormat.SVG);

            //Process proc = new Process();
            //proc.StartInfo.FileName = exportImage;
            //proc.StartInfo.UseShellExecute = true;
            //proc.Start();
            //Process.Start("explorer.exe", "/select, " + exportImage);

            using (PdfWriter writer = new PdfWriter(exportFile))
            {
                using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(writer))
                {
                    float cellMainWidth  = 176.5f;
                    float cellMainHeight = 80f;
                    float cellSpaceWidth = 3.2f;
                    pdfDocument.SetDefaultPageSize(PageSize.A4);
                    Document document = new Document(pdfDocument);
                    document.SetMargins(1.51f * 28.33f, 20f, 1.31f * 28.33f, 20f);
                    Barcode128 barcode = new Barcode128(pdfDocument);
                    barcode.SetCodeType(Barcode128.CODE_C);
                    barcode.SetCode("012345");
                    barcode.SetSize(14);
                    barcode.SetBaseline(15);
                    barcode.SetBarHeight(35f);
                    barcode.FitWidth(160f);
                    Image barcodeImage = new Image(barcode.CreateFormXObject(pdfDocument));
                    barcodeImage.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                    //barcodeImage.Scale(2.5f, 2f);
                    Paragraph text           = new Paragraph("TEST - TEST - TEST").SetTextAlignment(TextAlignment.CENTER).SetFontSize(14);
                    Paragraph num            = new Paragraph("012345").SetTextAlignment(TextAlignment.CENTER).SetFontSize(14);
                    Paragraph barcodeCombine = new Paragraph().Add(text).Add(barcodeImage);
                    Table     table          = new Table(5);
                    int       col            = 3;
                    int       row            = 8;
                    for (int i = 1; i <= 9; i++)
                    {
                        for (int j = 1; j <= 3; j++)
                        {
                            Cell cellMain = new Cell().SetBorder(Border.NO_BORDER);
                            cellMain.SetVerticalAlignment(VerticalAlignment.MIDDLE);
                            cellMain.SetHeight(cellMainHeight);
                            cellMain.SetWidth(cellMainWidth);
                            if (i == row && j == col)
                            {
                                cellMain.Add(text).Add(barcodeImage);
                            }
                            table.AddCell(cellMain);
                            if (j % 3 != 0)
                            {
                                Cell cellSpace = new Cell().SetBorder(Border.NO_BORDER);
                                cellSpace.SetHeight(cellMainHeight);
                                cellSpace.SetWidth(cellSpaceWidth);
                                cellSpace.SetMargin(0);
                                table.AddCell(cellSpace);
                            }
                        }
                    }


                    //cellMain.Add(num);

                    //table.AddCell(cellMain);

                    //cellMain = new Cell();
                    //cellMain.SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    //cellMain.SetHeight(cellMainHeight);
                    //cellMain.SetWidth(cellMainWidth);
                    //table.AddCell(cellMain);
                    //cellSpace = new Cell();
                    //cellSpace.SetHeight(cellMainHeight);
                    //cellSpace.SetWidth(cellSpaceWidth);
                    //table.AddCell(cellSpace);
                    //cellMain = new Cell();
                    //cellMain.SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    //cellMain.SetHeight(cellMainHeight);
                    //cellMain.SetWidth(cellMainWidth);
                    //table.AddCell(cellMain);
                    //cellMain = new Cell();
                    //cellMain.SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    //cellMain.SetHeight(cellMainHeight);
                    //cellMain.SetWidth(cellMainWidth);
                    //table.AddCell(cellMain);
                    document.Add(table);
                }
            }
            Process proc = new Process();

            proc.StartInfo.FileName        = exportFile;
            proc.StartInfo.UseShellExecute = true;
            proc.EnableRaisingEvents       = true;
            proc.Start();
            proc.Exited += Proc_Exited;

            //Spire.Pdf.PdfDocument document1 = new Spire.Pdf.PdfDocument();
            //document1.LoadFromFile(exportFile);
            //System.Drawing.Image img = document1.SaveAsImage(0, 300, 300);
            //img.Save(exportImage);
        }
コード例 #25
0
ファイル: ReportPrinter.cs プロジェクト: amitdumka/eStore
        public static string PrintCashBook(List <CashBook> cbList)
        {
            string fName = "cashBook_" + DateTime.Now.ToFileTimeUtc() + ".pdf";

            string fileName = Path.Combine(ReportHeaderDetails.WWWroot, fName);

            using PdfWriter pdfWriter = new PdfWriter(fileName);
            using PdfDocument pdfDoc  = new PdfDocument(pdfWriter);
            using Document doc        = new Document(pdfDoc, PageSize.A4);
            Paragraph header = new Paragraph(ReportHeaderDetails.FirstLine + "\n")
                               .SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER)
                               .SetFontColor(ColorConstants.RED);

            header.Add(ReportHeaderDetails.SecondLine + "\n");
            doc.Add(header);
            float[] columnWidths = { 1, 5, 15, 5, 5, 5 };
            Table   table        = new Table(UnitValue.CreatePercentArray(columnWidths)).SetBorder(new OutsetBorder(2));

            PdfFont f    = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            Cell    cell = new Cell(1, 6)
                           .Add(new Paragraph(ReportHeaderDetails.CashBook))
                           .SetFont(f)
                           .SetFontSize(13)
                           .SetFontColor(DeviceGray.WHITE)
                           .SetBackgroundColor(DeviceGray.BLACK)
                           .SetTextAlignment(TextAlignment.CENTER);

            table.AddHeaderCell(cell);

            Cell[] headerFooter = new Cell[] {
                new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("#")),
                new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Date").SetTextAlignment(TextAlignment.CENTER)),
                new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Particulars").SetTextAlignment(TextAlignment.CENTER)),
                new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("In").SetTextAlignment(TextAlignment.CENTER)),
                new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Out").SetTextAlignment(TextAlignment.CENTER)),
                new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Balance").SetTextAlignment(TextAlignment.CENTER))
            };

            Cell[] footer = new[]
            {
                new Cell(1, 4).Add(new Paragraph(ReportHeaderDetails.FirstLine + " / " + ReportHeaderDetails.SecondLine).SetFontColor(DeviceGray.GRAY)),
                new Cell(1, 2).Add(new Paragraph("D:" + DateTime.Now).SetFontColor(DeviceGray.GRAY)),
            };

            foreach (Cell hfCell in headerFooter)
            {
                table.AddHeaderCell(hfCell);
            }
            foreach (Cell hfCell in footer)
            {
                table.AddFooterCell(hfCell);
            }

            int count = 0;

            foreach (var item in cbList)

            {
                table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph((++count) + "")));
                table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(item.EDate.ToShortDateString())));
                table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(item.Particulars + "")));
                table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(item.CashIn.ToString("0.##"))));
                table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(item.CashOut.ToString("0.##"))));
                table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(item.CashBalance.ToString("0.##"))));
            }
            doc.Add(table);

            doc.Close();

            using PdfReader reader = new PdfReader(fileName);
            fName = "cashBook_" + (DateTime.Now.ToFileTimeUtc() + 1001) + ".pdf";
            using PdfWriter writer = new PdfWriter(Path.Combine(ReportHeaderDetails.WWWroot, fName));

            using PdfDocument pdfDoc2 = new PdfDocument(reader, writer);
            Document doc2 = new Document(pdfDoc2);

            int numberOfPages = pdfDoc2.GetNumberOfPages();

            for (int i = 1; i <= numberOfPages; i++)
            {
                // Write aligned text to the specified by parameters point
                doc2.ShowTextAligned(new Paragraph("Page " + i + " of " + numberOfPages),
                                     559, 806, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
            }

            doc2.Close();


            return(fName);
        }
コード例 #26
0
        /// <summary>
        /// Finds and sets the page numbers of links mapped to HTML headings in the specified PDF file.
        /// </summary>
        /// <param name="htmlToPdfFile">The HTML to PDF file.</param>
        internal static void SetHeadingPageNumbers(HtmlToPdfFile htmlToPdfFile)
        {
            using (PdfReader pdfReader = new PdfReader(htmlToPdfFile.PdfFilePath))
            {
                using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader))
                {
                    int pageCount = pdfDocument.GetNumberOfPages();
                    for (int i = 1; i <= pageCount; i++)
                    {
                        // get page
                        PdfPage pdfPage = pdfDocument.GetPage(i);

                        // get link annotations
                        IEnumerable <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>();
                        foreach (PdfLinkAnnotation linkAnnotation in linkAnnotations)
                        {
                            // get action
                            PdfDictionary action = linkAnnotation.GetAction();
                            if (action == null)
                            {
                                continue;
                            }

                            PdfName s = action.GetAsName(PdfName.S);
                            if (s != PdfName.URI)
                            {
                                continue;
                            }

                            PdfString uriPdfString = action.GetAsString(PdfName.URI);
                            if (!Uri.TryCreate(uriPdfString.GetValue(), UriKind.RelativeOrAbsolute, out Uri uri))
                            {
                                continue;
                            }

                            if (!uri.IsFile)
                            {
                                continue;
                            }

                            // get query string
                            NameValueCollection queryString = HttpUtility.ParseQueryString(uri.Query);

                            // ex. ?headingLevel={level}&headingText
                            string headingLevel = queryString["headingLevel"];
                            if (headingLevel == null)
                            {
                                continue;
                            }

                            if (!int.TryParse(headingLevel, out int level))
                            {
                                continue;
                            }

                            string headingText = queryString["headingText"];
                            if (headingText == null)
                            {
                                continue;
                            }

                            HtmlHeading htmlHeading = htmlToPdfFile.TitleAndHeadings.SingleOrDefault(x => (x.Level == level) && (x.Text == headingText));
                            if (htmlHeading == null)
                            {
                                continue;
                            }

                            htmlHeading.Page = i;
                        }
                    }
                }
            }
        }