private static byte[] CreateImagePdf() { MemoryStream byteStream = new MemoryStream(); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, byteStream); document.SetPageSize(PageSize.LETTER); document.Open(); Bitmap awtImg = new Bitmap(100, 100, PixelFormat.Format32bppRgb); Graphics g = Graphics.FromImage(awtImg); g.FillRectangle(new SolidBrush(Color.Green), 10, 10, 80, 80); g.Save(); Image itextImg = Image.GetInstance(awtImg, (BaseColor)null); document.Add(itextImg); document.Close(); byte[] pdfBytes = byteStream.ToArray(); return pdfBytes; }
public override byte[] CreatePdf(List<PdfContentParameter> contents, string[] images, int type) { var document = new Document(); float docHeight = document.PageSize.Height - heightOffset; document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); document.SetMargins(50, 50, 10, 40); var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); writer.PageEvent = new HeaderFooterHandler(type); document.Open(); document.Add(contents[0].Table); for (int i = 0; i < images.Length; i++) { document.NewPage(); float subtrahend = document.PageSize.Height - heightOffset; iTextSharp.text.Image pool = iTextSharp.text.Image.GetInstance(images[i]); pool.Alignment = 3; pool.ScaleToFit(document.PageSize.Width - (document.RightMargin * 2), subtrahend); //pool.ScaleAbsolute(document.PageSize.Width - (document.RightMargin * 2), subtrahend); document.Add(pool); } document.Close(); return output.ToArray(); }
public static byte[] MergePdfs(IEnumerable<byte[]> inputFiles) { MemoryStream outputStream = new MemoryStream(); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, outputStream); document.Open(); PdfContentByte content = writer.DirectContent; foreach (byte[] input in inputFiles) { PdfReader reader = new PdfReader(input); for (int i = 1; i <= reader.NumberOfPages; i++) { document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); PdfImportedPage page = writer.GetImportedPage(reader, i); int rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { content.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { content.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } } document.Close(); return outputStream.ToArray(); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); document.SetPageSize(PageSize.A5); document.SetMargins(36, 72, 108, 180); document.SetMarginMirroring(true); // step 3 document.Open(); // step 4 document.Add(new Paragraph( "The left margin of this odd page is 36pt (0.5 inch); " + "the right margin 72pt (1 inch); " + "the top margin 108pt (1.5 inch); " + "the bottom margin 180pt (2.5 inch).") ); Paragraph paragraph = new Paragraph(); paragraph.Alignment = Element.ALIGN_JUSTIFIED; for (int i = 0; i < 20; i++) { paragraph.Add("Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!" ); } document.Add(paragraph); document.Add(new Paragraph( "The right margin of this even page is 36pt (0.5 inch); " + "the left margin 72pt (1 inch).") ); } }
/// <summary> /// PDF Creator Helper With No Page Base (Don't want to write a page or report (header or footer) /// </summary> /// <param name="PageSize">Page Size - A4 is a default page size. Use Enum iTextSharp.text.PageSize</param> /// <param name="LandscapeMode">Do you want the pdf in landscape</param> /// <param name="MarginTop">Top Margin On The Page</param> /// <param name="MarginRight">Right Margin On The Page</param> /// <param name="MarginBottom">Bottom Margin On The Page</param> /// <param name="MarginLeft">Left Margin On The Page</param> /// <param name="PageEventHandler">A Page Event Class That Will Raise Any Events You Need</param> public PDFCreator(Rectangle PageSize, bool LandscapeMode, float MarginTop, float MarginRight, float MarginBottom, float MarginLeft, PageEventsBase PageEventHandler) { //create the instance of the ITextSharpDocument Doc = new Document(PageSize, MarginLeft, MarginRight, MarginTop, MarginBottom); //let's build the memory stream now Ms = new MemoryStream(); //let's create the new writer and attach the document Writer = PdfWriter.GetInstance(Doc, Ms); //add the page events to my custom class if (PageEventHandler != null) { Writer.PageEvent = PageEventHandler; } //if you want the pdf in landscape now, then rotate it if (LandscapeMode) { Doc.SetPageSize(PageSize.Rotate()); } //let's open the document so the developer can do whatever they wan't with it Doc.Open(); }
public static void GeneratePdfReport(string filepath) { FileStream fileStream = new FileStream(filepath, FileMode.Create); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, fileStream); document.SetPageSize(PageSize.A3); document.Open(); var paragraph = new Paragraph("Aggregated Sales Report", FontFactory.GetFont("Arial", 19, Font.BOLD)); paragraph.SpacingAfter = 20.0f; paragraph.Alignment = 1; document.Add(paragraph); PdfPTable mainTable = new PdfPTable(1); var reports = GetDayReports(); foreach (var dayReport in reports) { var headerCell = new PdfPCell(new Phrase("Date: " + dayReport.FormattedDate)); headerCell.BackgroundColor = new BaseColor(175, 166, 166); mainTable.AddCell(headerCell); var table = GenerateReportTable(dayReport); mainTable.AddCell(table); } document.Add(mainTable); document.Close(); }
/*public MemoryStream Process(IEnumerable<Student> students) { }*/ public MemoryStream Process(IEnumerable<ClassEnrollment> enrollments) { //Loop through each enrollment to process one report card per student var pdfReaders = enrollments.Select(enrollment => new PdfReader(Process(enrollment, enrollment.StudentGrades.ToList()).ToArray())).ToList(); //Now merge all the pdf streams into one document var outputStream = new MemoryStream(); var pdfDoc = new Document(); pdfDoc.SetMargins(0, 0, 0, 0); var writer = PdfWriter.GetInstance(pdfDoc, outputStream); pdfDoc.Open(); var pdfContentByte = writer.DirectContent; foreach (var reader in pdfReaders) { for (var page = 1; page <= reader.NumberOfPages; page++) { var importedPage = writer.GetImportedPage(reader, page); pdfDoc.SetPageSize(importedPage.BoundingBox); pdfDoc.NewPage(); pdfContentByte.AddTemplate(importedPage, 0, 0); } } outputStream.Flush(); pdfDoc.Close(); outputStream.Close(); return outputStream; }
public override void ExecuteResult(ControllerContext context) { if (ViewName == null) ViewName = context.RouteData.GetRequiredString("action"); context.Controller.ViewData.Model = Model; if (context.HttpContext.Request.QueryString["html"] != null && context.HttpContext.Request.QueryString["html"].ToLower().Equals("true")) { var view = ViewEngines.Engines.FindView(context, ViewName, null).View; var viewContext = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, context.HttpContext.Response.Output); view.Render(viewContext, context.HttpContext.Response.Output); } else { var memoryStream = new MemoryStream(); var document = new Document(new Rectangle(288f, 144f), 50, 50, 50, 30); document.SetPageSize(PageSize.A4); var instance = PdfWriter.GetInstance(document, memoryStream); instance.CloseStream = false; document.Open(); var view = ViewEngines.Engines.FindView(context, ViewName, null).View; var sb = new StringBuilder(); var writer = (TextWriter)new StringWriter(sb); var viewContext = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, writer); view.Render(viewContext, writer); var inp = (Stream)new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())); XMLWorkerHelper.GetInstance().ParseXHtml(instance, document, inp, (Stream)null); document.Close(); new FileStreamResult(new MemoryStream(memoryStream.ToArray()), "application/pdf") { FileDownloadName = FileName + ".pdf" }.ExecuteResult(context); } }
public void CreatePdf(Project project, Stream writeStream) { var document = new Document(); var writer = PdfWriter.GetInstance(document, writeStream); // landscape document.SetPageSize(PageSize.A4.Rotate()); document.SetMargins(36f, 36f, 36f, 36f); // 0.5 inch margins // metadata document.AddCreator("EstimatorX.com"); document.AddKeywords("estimation"); document.AddAuthor(project.Creator); document.AddSubject(project.Name); document.AddTitle(project.Name); document.Open(); AddName(project, document); AddDescription(project, document); AddAssumptions(project, document); AddFactors(project, document); AddTasks(project, document); AddSummary(project, document); writer.Flush(); document.Close(); }
public bool GraphConvertPdf(string savename,string savepath,string basepath,string basetype) { bool flag = true; Document doc = new Document(); savename = PdfClass.PdfFileNameConverter(savename); try { PdfWriter.GetInstance(doc, new FileStream(@savepath + "\\" + savename + ".pdf", FileMode.Create)); doc.Open(); int max = Directory.GetFiles(@basepath).Count(); for (int i = 0; i < max; i++) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Uri(@basepath + "\\" + i.ToString() + "." + basetype)); iTextSharp.text.Rectangle pagesize = new iTextSharp.text.Rectangle(image.Width / image.DpiX * 25.4f * 2.834f, image.Height / image.DpiY * 25.4f * 2.834f); doc.SetPageSize(pagesize); image.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height); image.SetAbsolutePosition(0f, 0f); doc.NewPage(); doc.Add(image); } doc.Close(); } catch { flag = false; } return flag; }
public string GereRelatorio() { PdfWriter escritor; string caminho; string nomeDoArquivoDeSaida; using (var servico = FabricaGenerica.GetInstancia().CrieObjeto<IServicoDeEmpresa>()) empresa = servico.Obtenha(FabricaDeContexto.GetInstancia().GetContextoAtual().EmpresaLogada.ID); nomeDoArquivoDeSaida = String.Concat(DateTime.Now.ToString("yyyyMMddhhmmss"), ".pdf"); caminho = String.Concat(HttpContext.Current.Request.PhysicalApplicationPath, UtilidadesWeb.PASTA_LOADS); _documento = new Document(); _documento.SetPageSize(PageSize.A4.Rotate()); escritor = PdfWriter.GetInstance(_documento, new FileStream(Path.Combine(caminho, nomeDoArquivoDeSaida), FileMode.Create)); escritor.PageEvent = new Ouvinte(_Fonte1, _Fonte2, _Fonte3, _Fonte4, empresa); escritor.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); escritor.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfName.NONE); _documento.Open(); EscrevaProcessosNoDocumento(); _documento.Close(); return nomeDoArquivoDeSaida; }
void startGenerateReport() { if (!string.IsNullOrEmpty(txtPath.Text)) { document = new Document(PageSize.A3, 0, 0, 0, 0); document.SetPageSize(PageSize.A3.Rotate()); document.SetMargins(0, 0, 60f, 40f); var tempFileName = ("E:\\report.pdf"); fileStream = new System.IO.FileStream(tempFileName, System.IO.FileMode.Create); writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fileStream); var logoSetting = _reportSettingRepository.GetKeyValue(Repository.Utils.ReportSettingsKeys.Logo); iTextEvents = new ITextEvents(); iTextEvents.Logo = logoSetting != null ? logoSetting.Value : string.Empty; writer.PageEvent = iTextEvents; document.Open(); var cb = writer.DirectContent; drawFrontPage(); var drawGranulometryOnPDF = new DrawGranulometryOnPDF(_granulometryControl, document, progressBar1, panel1, iTextEvents); drawGranulometryOnPDF.DrawCompleted += drawGranulometryOnPDF_DrawCompleted; } else { MessageBox.Show("Please provide path"); } }
public string MergeMultiplePDFsToPDF(string[] fileList, string outMergeFile) { string returnStr = ""; try { int f = 0; // we create a reader for a certain document PdfReader reader = new PdfReader(fileList[f]); // we retrieve the total number of pages int n = reader.NumberOfPages; //There are " + n + " pages in the original file. // step 1: creation of a document-object Document document = new Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create)); // step 3: we open the document document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int rotation; // step 4: we add content while (f < fileList.Length) { int i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } //Processed page i } f++; if (f < fileList.Length) { reader = new PdfReader(fileList[f]); // we retrieve the total number of pages n = reader.NumberOfPages; //There are " + n + " pages in the original file. } } // step 5: we close the document document.Close(); returnStr = "Succeed!"; } catch (Exception e) { returnStr += e.Message + "<br />"; returnStr += e.StackTrace; } return returnStr; }
/// <summary> /// Merges multiple pdf files into 1 pdf file. /// </summary> /// <param name="FilesToMerge">Files to merger (Byte array for each file)</param> /// <returns>1 file with all the files passed in</returns> public static byte[] MergeFiles(IEnumerable<byte[]> FilesToMerge) { //Declare the memory stream to use using (var MemoryStreamToWritePdfWith = new MemoryStream()) { //declare the new document which we will merge all the files into using (var NewFileToMergeIntoWith = new Document()) { //holds the byte array which we will return byte[] ByteArrayToReturn; //declare the pdf copy to write the data with using (var PdfCopyWriter = new PdfCopy(NewFileToMergeIntoWith, MemoryStreamToWritePdfWith)) { //set the page size of the new file //NewFileToMergeIntoWith.SetPageSize(PageSize.GetRectangle("Letter").Rotate().Rotate()); //go open the new file that we are writing into NewFileToMergeIntoWith.Open(); //now loop through all the files we want to merge foreach (var FileToMerge in FilesToMerge) { //declare the pdf reader so we can copy it using (var PdfFileReader = new PdfReader(FileToMerge)) { //figure out how many pages are in this pdf, so we can add each of the pdf's int PdfFilePageCount = PdfFileReader.NumberOfPages; // loop over document pages (start with page 1...not a 0 based index) for (int i = 1; i <= PdfFilePageCount; i++) { //set the file size for this page NewFileToMergeIntoWith.SetPageSize(PdfFileReader.GetPageSize(i)); //add a new page for the next page NewFileToMergeIntoWith.NewPage(); //now import the page PdfCopyWriter.AddPage(PdfCopyWriter.GetImportedPage(PdfFileReader, i)); } } } //now close the new file which we merged everyting into NewFileToMergeIntoWith.Close(); //grab the buffer and throw it into a byte array to return ByteArrayToReturn = MemoryStreamToWritePdfWith.GetBuffer(); //flush out the memory stream MemoryStreamToWritePdfWith.Flush(); } //now return the byte array return ByteArrayToReturn; } } }
public void Build() { iTextSharp.text.Document doc = null; try { // Initialize the PDF document doc = new Document(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "\\ScienceReport.pdf", System.IO.FileMode.Create)); // Set margins and page size for the document doc.SetMargins(50, 50, 50, 50); // There are a huge number of possible page sizes, including such sizes as // EXECUTIVE, POSTCARD, LEDGER, LEGAL, LETTER_LANDSCAPE, and NOTE doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height)); // Add metadata to the document. This information is visible when viewing the // document properities within Adobe Reader. doc.AddTitle("My Science Report"); doc.AddCreator("M. Lichtenberg"); doc.AddKeywords("paper airplanes"); // Add Xmp metadata to the document. this.CreateXmpMetadata(writer); // Open the document for writing content doc.Open(); // Add pages to the document this.AddPageWithBasicFormatting(doc); this.AddPageWithInternalLinks(doc); this.AddPageWithBulletList(doc); this.AddPageWithExternalLinks(doc); this.AddPageWithImage(doc, System.IO.Directory.GetCurrentDirectory() + "\\FinalGraph.jpg"); // Add page labels to the document iTextSharp.text.pdf.PdfPageLabels pdfPageLabels = new iTextSharp.text.pdf.PdfPageLabels(); pdfPageLabels.AddPageLabel(1, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Basic Formatting"); pdfPageLabels.AddPageLabel(2, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Internal Links"); pdfPageLabels.AddPageLabel(3, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Bullet List"); pdfPageLabels.AddPageLabel(4, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "External Links"); pdfPageLabels.AddPageLabel(5, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Image"); writer.PageLabels = pdfPageLabels; } catch (iTextSharp.text.DocumentException dex) { // Handle iTextSharp errors } finally { // Clean up doc.Close(); doc = null; } }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); var document = new Document(); document.SetPageSize(new Rectangle(72 * W, 72 * H)); document.SetMargins(14f, 0f, 3.6f, 1f); var w = PdfWriter.GetInstance(document, Response.OutputStream); document.Open(); dc = w.DirectContent; var ctl = new MailingController {UseTitles = titles, UseMailFlags = useMailFlags}; IEnumerable<MailingController.MailingInfo> q = null; switch (format) { case "Individual": case "GroupAddress": q = ctl.FetchIndividualList(sort, qid); break; case "FamilyMembers": case "Family": q = ctl.FetchFamilyList(sort, qid); break; case "ParentsOf": q = ctl.FetchParentsOfList(sort, qid); break; case "CouplesEither": q = ctl.FetchCouplesEitherList(sort, qid); break; case "CouplesBoth": q = ctl.FetchCouplesBothList(sort, qid); break; } AddLabel(document, "=========", $"{Util.UserName}\n{q.Count()},{DateTime.Now:g}", String.Empty); foreach (var m in q) { var label = m.LabelName; if (m.CoupleName.HasValue() && format.StartsWith("Couples")) label = m.CoupleName; var address = ""; if (m.MailingAddress.HasValue()) address = m.MailingAddress; else { var sb = new StringBuilder(m.Address); if (m.Address2.HasValue()) sb.AppendFormat("\n{0}", m.Address2); sb.AppendFormat("\n{0}", m.CSZ); address = sb.ToString(); } AddLabel(document, label, address, Util.PickFirst(m.CellPhone.FmtFone("C "), m.HomePhone.FmtFone("H "))); } document.Close(); }
bool IPDFConverter.ConvertToPDF(string Src, out string PDFFile) { System.IO.FileInfo info = new System.IO.FileInfo(Src); PDFFile = Src; bool succeeded = true; Gnome.Vfs.Uri uri = new Gnome.Vfs.Uri(Gnome.Vfs.Uri.GetUriFromLocalPath(info.FullName)); Gnome.Vfs.MimeType mime = new Gnome.Vfs.MimeType(uri); if (mime != null && mime.Name.ToLower().StartsWith("image")) { Document document = null; try { PDFFile = String.Format("/tmp/{0}.pdf", info.Name); Image logo = Image.GetInstance(info.FullName); // step 1: creation of a document-object //Rectangle pageSize = new Rectangle(logo.GetRectangle(0, 0)); document = new Document(); document.SetMargins(0, 0, 0, 0); document.SetPageSize(new Rectangle(logo.Width, logo.Height)); // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream(PDFFile, FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we Add some paragraphs to the document document.Add(logo); } catch(DocumentException de) { Console.Error.WriteLine(de.Message); } catch(IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); } if (! System.IO.File.Exists(PDFFile)) { PDFFile = null; succeeded = false; } return succeeded; }
public void ConvertImagesToPdf(IProgress<TaskProgress> progress) { if (_sourceFileList == null || _sourceFileList.Count == 0) { throw new ArgumentException("At least 1 source file must be specified"); } if (string.IsNullOrWhiteSpace(_outputFilePath)) { throw new ArgumentException("Invalid output file name"); } using (var outputStream = new MemoryStream()) { int pageCount = 0; using (Document document = new Document()) { document.SetMargins(0, 0, 0, 0); PdfWriter.GetInstance(document, outputStream).SetFullCompression(); document.Open(); foreach (string sourceFilePath in _sourceFileList) { iTextSharp.text.Rectangle pageSize = null; using (var sourceImage = new Bitmap(sourceFilePath)) { pageSize = new iTextSharp.text.Rectangle(0, 0, sourceImage.Width, sourceImage.Height); } document.SetPageSize(pageSize); document.NewPage(); using (var ms = new MemoryStream()) { var image = iTextSharp.text.Image.GetInstance(sourceFilePath); document.Add(image); ++pageCount; progress.Report(new TaskProgress() { ProcessedInputCount = pageCount, StatusMessage = $"{pageCount} of {_sourceFileList.Count} images have been added", CompletedPercentage = (pageCount / _sourceFileList.Count) * 100 }); } } } progress.Report(new TaskProgress() { ProcessedInputCount = pageCount, StatusMessage = $"Saving files...", CompletedPercentage = 100 }); File.WriteAllBytes(_outputFilePath, outputStream.ToArray()); progress.Report(new TaskProgress() { ProcessedInputCount = pageCount, StatusMessage = $"PDF file has been created.", CompletedPercentage = 100 }); progress.Report(new TaskProgress() { ProcessedInputCount = pageCount, StatusMessage = $"Handling input files...", CompletedPercentage = 0 }); HandleInputFiles(); progress.Report(new TaskProgress() { ProcessedInputCount = pageCount, StatusMessage = $"Operation completed successfully", CompletedPercentage = 100 }); } }
public static void CreatePdf(string fileName) { Document document = new Document(); FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate); PdfWriter.GetInstance(document, stream); document.SetPageSize(PageSize.A5); document.SetMargins(36, 72, 108, 180); document.SetMarginMirroringTopBottom(true); document.Open(); document.Add(new Paragraph("Hello World")); document.Close(); }
public static String Concatenate(String[] pdfs) { String temporaryFilePath = GetTemporaryFile(); try { int pdfFileIndex = 0; PdfReader reader = new PdfReader(pdfs[pdfFileIndex]); int totalPages = reader.NumberOfPages; Document document = new Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(temporaryFilePath, FileMode.Create)); // step 3: we open the document document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; while (true) { int i = 0; while (i < totalPages) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } pdfFileIndex++; if (pdfFileIndex < pdfs.Length) { reader = new PdfReader(pdfs[pdfFileIndex]); // we retrieve the total number of pages totalPages = reader.NumberOfPages; } else break; } // step 5: we close the document document.Close(); } catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } return temporaryFilePath; }
public void ExportPersonalDataPDF(DataTable dataTable, String savePath, string title) { System.IO.FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document document = new iTextSharp.text.Document(); document.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); //Report Header BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(title.ToUpper())); document.Add(prgHeading); //Author Paragraph prgAuthor = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); prgAuthor.Alignment = Element.ALIGN_RIGHT; prgAuthor.Add(new Chunk("Author : GASF")); prgAuthor.Add(new Chunk("\nRun Date : " + DateTime.Now.ToShortDateString())); document.Add(prgAuthor); //Add a line seperation Paragraph p = new Paragraph(); document.Add(p); //Add line break document.Add(new Chunk("\n")); //Write the table PdfPTable table = new PdfPTable(dataTable.Columns.Count); //Table header BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); for (int i = 0; i < dataTable.Columns.Count; i++) { document.Add(new Chunk(dataTable.Columns[i].ColumnName + " : " + dataTable.Rows[0][i].ToString())); document.Add(new Chunk("\n")); } document.Add(table); document.Close(); writer.Close(); fs.Close(); }
public static List <byte[]> Split(PdfReader reader) { int p = 0; Document document; var data = new List <byte[]>(); for (p = 1; p <= reader.NumberOfPages; p++) { using (MemoryStream memoryStream = new MemoryStream()) { document = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_2); writer.CompressionLevel = PdfStream.BEST_COMPRESSION; writer.SetFullCompression(); document.SetPageSize(reader.GetPageSize(p)); document.NewPage(); document.Open(); document.AddDocListener(writer); PdfContentByte cb = writer.DirectContent; PdfImportedPage pageImport = writer.GetImportedPage(reader, p); int rot = reader.GetPageRotation(p); if (rot == 90 || rot == 270) { cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height); } else { cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0); } document.Close(); document.Dispose(); //File.WriteAllBytes(DestinationFolder + "/" + p + ".pdf", memoryStream.ToArray()); data.Add(memoryStream.ToArray()); if (OnSplitProcess != null) { OnSplitProcess(p, null); } } } reader.Close(); reader.Dispose(); return(data); }
private byte[] CreateContent(PdfContentParameter content) { var document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); document.SetMargins(50, 50, 10, 40); var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); document.Open(); document.Add(content.Table); document.Close(); return output.ToArray(); }
public void CreatePages(Models.Document documentTemplate, string outputFile) { _itextDocument = new iTextSharp.text.Document(); _itextPDFWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(_itextDocument, new System.IO.FileStream(outputFile, System.IO. FileMode. Create)); _itextPDFWriter.PdfVersion = PdfWriter.VERSION_1_7; _itextPDFWriter.Open(); PdfContentByte itextContent = _itextPDFWriter.DirectContent; int pageCounter = 0; foreach (Models.Page pageTemplate in documentTemplate.Pages) { pageCounter++; if (pageTemplate.Bleeding.Points > 0) { _itextPDFWriter.SetBoxSize("bleed", new iTextSharp.text.Rectangle(0, 0, pageTemplate.Width.Points, pageTemplate.Height.Points)); } Rectangle pageLayoutRectangle = new iTextSharp.text.Rectangle(-pageTemplate.Bleeding.Points, -pageTemplate.Bleeding.Points, pageTemplate.Width.Points + pageTemplate.Bleeding.Points, pageTemplate.Height.Points + pageTemplate.Bleeding.Points); _itextPDFWriter.PageEmpty = false; _itextDocument.SetPageSize(pageLayoutRectangle); if (!_itextDocument.IsOpen()) { _itextDocument.Open(); } PdfPage page = new PdfPage(this, itextContent); page.Render(pageTemplate); itextContent.PdfDocument.NewPage(); } }
public bool CreateReport(ReportObject.PawnTicketAddendum pawnTicketAddendum) { bool isSuccessful = false; var document = new iTextSharp.text.Document(PageSize.LETTER); try { //set up RunReport event overrides & create doc _pageCount = 1; //PawnTicketAddendumDocument events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); AddndmPageEvents events = new AddndmPageEvents(); writer.PageEvent = events; //MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 100, document.PageSize.Height - (50)); //columns.AddSimpleColumn(-150, document.PageSize.Width + 76); //set up tables, etc... PdfPTable table = new PdfPTable(8); table.WidthPercentage = 85;// document.PageSize.Width; runReport = new RunReport(); document.Open(); document.SetPageSize(PageSize.LETTER); document.SetMargins(-100, -100, 10, 45); ReportHeader(table, 8); //here add detail WriteDetail(table, pawnTicketAddendum); document.Add(table); document.Close(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public void ExportRATCertificatePDF(String savePath, string title) { System.IO.FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document document = new iTextSharp.text.Document(); document.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); //Report Header BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(title.ToUpper())); document.Add(prgHeading); //Author Paragraph prgAuthor = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); prgAuthor.Alignment = Element.ALIGN_RIGHT; prgAuthor.Add(new Chunk("\nDate : " + DateTime.Now.ToShortDateString())); document.Add(prgAuthor); //Add a line seperation Paragraph p = new Paragraph(); document.Add(p); //Add line break document.Add(new Chunk("\n")); document.Add(new Chunk("Through my mighty presence it is fortold that SIR/LADY ............................. " + "is studnet in year ........... at University ..................,section ...................,year of study ............,tax/budget ........\n")); document.Add(new Chunk("\n")); document.Add(new Chunk("\n")); document.Add(new Chunk("\n")); document.Add(new Chunk("Sign Here :\n")); Paragraph stamp = new Paragraph(); BaseFont btnStamp = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); stamp.Alignment = Element.ALIGN_RIGHT; stamp.Add(new Chunk("Stamp : ")); document.Add(stamp); document.Close(); writer.Close(); fs.Close(); }
public void ExtractPages(string inputFile, string outputFile, List<int> extractPages, System.Windows.Forms.ProgressBar progres) { if (inputFile == outputFile) { System.Windows.Forms.MessageBox.Show("Nie możesz użyć pliku wejściowego jako wyjściowego do zapisu."); } PdfReader inputPDF = new PdfReader(inputFile); Document doc = new Document(); PdfReader reader = new PdfReader(inputFile); progres.Maximum = reader.NumberOfPages; using (MemoryStream memoryStream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream); doc.Open(); doc.AddDocListener(writer); for (int i = 1; i <= reader.NumberOfPages; i++) { progres.Value = i; if (extractPages.FindIndex(s => s == i) == -1) continue; doc.SetPageSize(reader.GetPageSize(i)); doc.NewPage(); PdfContentByte cb = writer.DirectContent; PdfImportedPage pageImport = writer.GetImportedPage(reader, i); int rot = reader.GetPageRotation(i); if (rot == 90 || rot == 270) { cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0); } } reader.Close(); doc.Close(); try { File.WriteAllBytes(outputFile, memoryStream.ToArray()); } catch { throw new Exception("Błąd przy próbie zapisu do pliku. Upewnij się iż żaden inny proces obecnie go nie używa."); } } }
private string GereInformacoesUteisParaOArquivoDeSaidaDoRelatorio() { using (var servico = FabricaGenerica.GetInstancia().CrieObjeto<IServicoDeEmpresa>()) empresa = servico.Obtenha(FabricaDeContexto.GetInstancia().GetContextoAtual().EmpresaLogada.ID); var nomeDoArquivoDeSaida = String.Concat(DateTime.Now.ToString("yyyyMMddhhmmss"), ".pdf"); var caminho = String.Concat(HttpContext.Current.Request.PhysicalApplicationPath, UtilidadesWeb.PASTA_LOADS); _documento = new Document(); _documento.SetPageSize(PageSize.A4.Rotate()); var escritor = PdfWriter.GetInstance(_documento, new FileStream(Path.Combine(caminho, nomeDoArquivoDeSaida), FileMode.Create)); escritor.PageEvent = new GeradorDeRelatorioPorColidencia.Ouvinte(_Fonte1, _Fonte2, _Fonte3, _Fonte4, empresa, _NumeroDaRevistaSelecionada, _DataPublicacao); escritor.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); escritor.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfName.NONE); return nomeDoArquivoDeSaida; }
public bool CreateReport() { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate()); try { //set up RunReport event overrides & create doc LayawayPickingSlip events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 125, MultiColumnText.AUTOMATIC); columns.AddSimpleColumn(-30, document.PageSize.Width + 20); //set up tables, etc... PdfPTable table = new PdfPTable(7); table.WidthPercentage = 85;// document.PageSize.Width; var gif = Image.GetInstance(Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new LayawayRunReports(); document.Open(); document.SetPageSize(PageSize.HALFLETTER.Rotate()); document.SetMargins(-100, -100, 10, 45); document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy"))); ReportDetail(table); columns.AddElement(table); document.Add(columns); document.Close(); //nnaeme //OpenFile(ReportObject.ReportTempFileFullName); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public string SetSize(string sourceFile, string pSize, string targetPath) { try { string file = GetFullPath(sourceFile); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file); int n = reader.NumberOfPages; Rectangle pageSize = PageSize.GetRectangle(pSize); iTextSharp.text.Document document = new iTextSharp.text.Document(pageSize); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(GetFullPath(targetPath), System.IO.FileMode.Create)); document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; iTextSharp.text.pdf.PdfImportedPage page; int rotation; int i = 0; reader = new iTextSharp.text.pdf.PdfReader(file); n = reader.NumberOfPages; while (i < n) { i++; document.SetPageSize(pageSize); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else if ((rotation == 270)) { cb.AddTemplate(page, 0f, 1f, -1f, 0f, reader.GetPageSizeWithRotation(i).Width, 0f); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } document.Close(); return(""); } catch (Exception e) { return(e.Message); } }
public void WriteTextWithWordSpacing() { Document document = new Document(); FileStream output = new FileStream(TARGET + "textWithWorldSpacing.pdf", FileMode.Create); PdfWriter writer = PdfWriter.GetInstance(document, output); document.Open(); document.SetPageSize(PageSize.A4); document.NewPage(); writer.DirectContent.SetWordSpacing(10); ColumnText columnText = new ColumnText(writer.DirectContent); columnText.SetSimpleColumn(new Rectangle(30, 0, document.PageSize.Right, document.PageSize.Top - 30)); columnText.UseAscender = true; columnText.AddText(new Chunk("H H H H H H H H H !", new Font(fontWithToUnicode, 30))); columnText.Go(); document.Close(); }
private void btnPDF_Click(object sender, EventArgs e) { new Forms.GenerateReportStatusForm(granulometryControl1, correlationMatrixControl1.CorrelationMatrixList, krigingSelectionControl1) .ShowDialog(); return; Document document = new Document(PageSize.A3, 0, 0, 0, 0); document.SetPageSize(PageSize.A3.Rotate()); document.SetMargins(0, 0, 13f, 20f); var tempFileName = ("E:\\report.pdf"); var fileStream = new System.IO.FileStream(tempFileName, System.IO.FileMode.Create); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fileStream); document.Open(); var cb = writer.DirectContent; PdfPTable tblKrigingImage = new PdfPTable(1); tblKrigingImage.DefaultCell.Padding = 0; tblKrigingImage.DefaultCell.PaddingTop = 100; tblKrigingImage.DefaultCell.Border = 0; foreach (var item in granulometryControl1.Rows) { if (item != null) { if (item.KrigingField != null && !string.IsNullOrEmpty(item.KrigingField.Image)) { // var ctrl = new KrigingViewerControl(item.ColorsList); // var coverImage = iTextSharp.text.Image.GetInstance(fm.FileName); // tblKrigingImage.AddCell(coverImage); } } } document.Add(tblKrigingImage); document.Close(); writer.Close(); fileStream.Close(); }
public static Stream JoinPdfs(bool InsertBlankPages, List<Stream> Pdfs) { if (Pdfs.Count == 0) throw new System.ArgumentNullException(nameof(Pdfs)); // Only One PDF - Possible Reference Bug v's Memory/Speed (Returning Param Memory Stream) if (Pdfs.Count == 1) return Pdfs[0]; // Join Pdfs var msBuilder = new MemoryStream(); var pdfLastPageSize = PageSize.A4; var pdfDoc = new Document(); var pdfCopy = new PdfSmartCopy(pdfDoc, msBuilder); pdfDoc.Open(); pdfCopy.CloseStream = false; for (int i = 0; i < Pdfs.Count; i++) { var pdf = Pdfs[i]; var pdfReader = new PdfReader(pdf); if (InsertBlankPages && (pdfCopy.CurrentPageNumber % 2) == 0) { pdfCopy.AddPage(pdfLastPageSize, 0); } for (int indexPage = 1; indexPage <= pdfReader.NumberOfPages; indexPage++) { pdfLastPageSize = pdfReader.GetPageSizeWithRotation(indexPage); var page = pdfCopy.GetImportedPage(pdfReader, indexPage); pdfDoc.SetPageSize(pdfLastPageSize); pdfCopy.AddPage(page); } pdfReader.Close(); } pdfDoc.Close(); pdfCopy.Close(); msBuilder.Position = 0; return msBuilder; }
// based on http://itextsharp.sourceforge.net/examples/Encrypt.cs public string ModifyPermissions(string PathSource, string PathTarget, string UserPassword, List <int> Permissons) { try { int PDFpermisson = 0; foreach (int permisson in Permissons) { PDFpermisson = PDFpermisson | permisson; } iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(PathSource); int n = reader.NumberOfPages; iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create)); writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, UserPassword, null, (int)PDFpermisson); // step 3: we open the document document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; iTextSharp.text.pdf.PdfImportedPage page; int rotation; int i = 0; // step 4: we add content while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } document.Close(); return(""); } catch (Exception e) { return(e.Message); } }
public static void MergeFiles(string destinationFile, List<string> files, bool removeMergedFiles) { try { var f = 0; var reader = new PdfReader(files.First()); var numberOfPages = reader.NumberOfPages; var document = new Document(reader.GetPageSizeWithRotation(1)); var writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create)); document.Open(); var content = writer.DirectContent; while (f < files.Count) { var i = 0; while (i < numberOfPages) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); var page = writer.GetImportedPage(reader, i); var rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) content.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); else content.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } f++; if (f < files.Count) { reader = new PdfReader(files[f]); numberOfPages = reader.NumberOfPages; } } document.Close(); if (removeMergedFiles) { DeleteMergedFiles(files); } } catch (Exception e) { var strOb = e.Message; } }
public ExportReport() { xdoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "\\AppTemplate\\report.xml"); pdfDoc = new Document(PageSize.A4, 0, 0, 0, 0); Rectangle rect = new Rectangle(794, 1123); pdfDoc.SetPageSize(rect); pdfDoc.SetMargins(0, 0, 20, 0); BaseFont.AddToResourceSearch("iTextAsian.dll"); BaseFont.AddToResourceSearch("iTextAsianCmaps.dll"); BaseFont bsFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); fontTitle = new Font(bsFont, 20); fontContent = new Font(bsFont, 12); fontLabel = new Font(bsFont, 12); fontTableRemark = new Font(bsFont, 14); fontLabel.SetStyle(Font.BOLD); fontTitle.SetStyle(Font.BOLD); fontTableRemark.SetStyle(Font.BOLD); }
/// <summary> /// 用report.xml的xdocument实例化 /// </summary> /// <param name="doc">report内容</param> public AbsExportPDF(XDocument doc) { xdoc = doc; pdfDoc = new Document(PageSize.A4, 0, 0, 0, 0); Rectangle rect = new Rectangle(794, 1123); pdfDoc.SetPageSize(rect); pdfDoc.SetMargins(0, 0, 20, 0); BaseFont.AddToResourceSearch("iTextAsian.dll"); BaseFont.AddToResourceSearch("iTextAsianCmaps.dll"); BaseFont bsFont; bsFont = BaseFont.CreateFont(@"c:\WINDOWS\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); fontTitle = new Font(bsFont, 20); fontContent = new Font(bsFont, 12); fontLabel = new Font(bsFont, 12); fontTableRemark = new Font(bsFont, 14); fontLabel.SetStyle(Font.BOLD); fontTitle.SetStyle(Font.BOLD); fontTableRemark.SetStyle(Font.BOLD); }
}//Скрывает интерфейс разных методов прогноза private void PdfToolStripMenuItem_Click(object sender, EventArgs e) { //Объект документа пдф iTextSharp.text.Document doc = new iTextSharp.text.Document(); doc.SetPageSize(PageSize.A4.Rotate()); try { //Создаем объект записи пдф-документа в файл PdfWriter.GetInstance(doc, new FileStream("pdfTables.pdf", FileMode.Create)); } catch (IOException) { MessageBox.Show("Пожалуйста, для сохранения файла, закройте файл pdf и нажмите ОК"); try { PdfWriter.GetInstance(doc, new FileStream("pdfTables.pdf", FileMode.Create)); } catch (Exception) { MessageBox.Show("Не удалост вывести в pdf файл!"); return; } } //Открываем документ doc.Open(); //Определение шрифта необходимо для сохранения кириллического текста //Иначе мы не увидим кириллический текст //Если мы работаем только с англоязычными текстами, то шрифт можно не указывать string FONT_LOCATION = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.TTF"); //определяем В СИСТЕМЕ(чтобы не копировать файл) расположение шрифта arial.ttf BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //создаем шрифт iTextSharp.text.Font fontParagraph = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL); //регистрируем + можно задать параметры для него(17 - размер, последний параметр - стиль) //Создаем объект таблицы и передаем в нее число столбцов таблицы из нашего датасета PdfPTable table = new PdfPTable(dataGridView1.ColumnCount); //MyDataSet.Tables[i].Columns.Count); //Добавим в таблицу общий заголовок PdfPCell cell = new PdfPCell(new Phrase("")); //cell.Colspan = dataGridView1.ColumnCount; //cell.HorizontalAlignment = 1; ////Убираем границу первой ячейки, чтобы был как заголовок //cell.Border = 0; //table.AddCell(cell); //Сначала добавляем заголовки таблицы for (int j = 0; j < dataGridView1.ColumnCount; j++) { cell = new PdfPCell(new Phrase(new Phrase(dataGridView1.Columns[j].HeaderText, fontParagraph))); //Фоновый цвет (необязательно, просто сделаем по красивее) cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell); } //Добавляем все остальные ячейки for (int j = 0; j < dataGridView1.RowCount - 1; j++) { for (int k = 0; k < dataGridView1.ColumnCount; k++) { if (dataGridView1.Rows[j].Cells[k].Value != null) { table.AddCell(new Phrase(Math.Round(Convert.ToDouble(dataGridView1.Rows[j].Cells[k].Value), 2).ToString(), fontParagraph)); } else { table.AddCell(new Phrase(" ", fontParagraph)); } } } //if (ComboBoxMethod.SelectedIndex != 1 && textBoxErrorIndic.Text != "") //fileCSV += "Среднеквадратическая ошибка расчёта ;" + textBoxErrorIndic.Text + ";"; //table.AddCell(new Phrase(Math.Round(Convert.ToDouble(textBoxErrorIndic.Text), 2).ToString(), fontParagraph)); // table.AddCell(new Phrase("123", fontParagraph)); /**/ chart1.SaveImage(Application.StartupPath + @"\1.bmp", System.Drawing.Imaging.ImageFormat.Bmp); iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Application.StartupPath + @"/1.bmp"); jpg.Alignment = iTextSharp.text.Image.ALIGN_CENTER; //Добавляем таблицу в документ doc.Add(table); if (ComboBoxMethod.SelectedIndex != 1 && textBoxErrorIndic.Text != "") { doc.Add(new Phrase("\n Среднеквадратическая ошибка прогноза: " + Math.Round(Convert.ToDouble(textBoxErrorIndic.Text), 3).ToString(), fontParagraph)); } if (ComboBoxMethod.SelectedIndex == 2 && textBoxErrorForecast.Text != "") { doc.Add(new Phrase("\n Ошибка прогноза: " + Math.Round(Convert.ToDouble(textBoxErrorForecast.Text), 3).ToString(), fontParagraph)); } doc.NewPage(); jpg.ScalePercent(80); doc.Add(jpg); //Закрываем документ doc.Close(); Process.Start("pdfTables.pdf"); }
public bool CreateReport(ReportObject.RetailSaleListing RetailSaleListingData, ReportObject.RetailSaleCustomer RetailSaleCustomerData, List <ReportObject.RetailSaleMerchandise> RetailSaleMerchandiseList, List <ReportObject.RetailSaleTender> RetailSaleTenderList, List <ReportObject.RetailSaleHistory> RetailSaleHistoryList) { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER.Rotate()); try { //set up RunReport event overrides & create doc _pageCount = 1; RetailSaleInquiryDetailReport events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 100, document.PageSize.Height - (50)); float pageLeft = document.PageSize.Left; float pageright = document.PageSize.Right; columns.AddSimpleColumn(-75, document.PageSize.Width + 76); //set up tables, etc... PdfPCell cell = new PdfPCell(); Image gif = Image.GetInstance(Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new RunReport(); document.Open(); document.SetPageSize(PageSize.LETTER.Rotate()); document.SetMargins(-100, -100, 10, 45); document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy")); PdfPTable customerTable = new PdfPTable(12); customerTable.WidthPercentage = 100;// document.PageSize.Width; WriteRetailSaleCustomerSectionHeader(customerTable, RetailSaleCustomerData); WriteRetailSaleCustomerSection(customerTable, 12, RetailSaleCustomerData); columns.AddElement(customerTable); PdfPTable transactionDetailTable = new PdfPTable(12); transactionDetailTable.WidthPercentage = 100;// document.PageSize.Width; WriteRetailSaleTransactionDetailSectionHeader(transactionDetailTable, RetailSaleListingData); WriteRetailSaleTransactionDetailSection(transactionDetailTable, 12, RetailSaleListingData, RetailSaleTenderList); columns.AddElement(transactionDetailTable); PdfPTable merchandiseTable = new PdfPTable(12); merchandiseTable.WidthPercentage = 100;// document.PageSize.Width; WriteRetailSaleMerchandiseSectionHeader(merchandiseTable, RetailSaleMerchandiseList); WriteRetailSaleMerchandiseSection(merchandiseTable, 12, RetailSaleMerchandiseList); columns.AddElement(merchandiseTable); PdfPTable retailSaleHistoryTable = new PdfPTable(12); retailSaleHistoryTable.WidthPercentage = 100;// document.PageSize.Width; WriteRetailSaleHistorySectionHeader(retailSaleHistoryTable, RetailSaleHistoryList); WriteRetailSaleHistorySectionColumnHeaders(retailSaleHistoryTable, RetailSaleHistoryList); WriteRetailSaleHistorySection(retailSaleHistoryTable, 12, RetailSaleHistoryList); columns.AddElement(retailSaleHistoryTable); //here add detail document.Add(columns); document.Close(); OpenFile(ReportObject.ReportTempFileFullName); //CreateReport(_icn, _description, theData); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public bool CreateReport() { bool isSuccessful = false; document = new Document(PageSize.LETTER); try { rowNumbers = new List <int>(); //set up RunReport event overrides & create doc string reportFileName = Path.GetFullPath(_ReportObject.ReportTempFileFullName); if (!Directory.Exists(Path.GetDirectoryName(reportFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(reportFileName)); } PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportFileName, FileMode.Create)); writer.PageEvent = this; //set up tables, etc... int columns = 8; if (!_Records[0].Table.Columns.Contains("colRefurb")) { columns = 7; } else { isRefurb = true; } PdfPTable table = new PdfPTable(columns); Image gif = Image.GetInstance(Resources.logo, BaseColor.WHITE); _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL); _reportFontLargeBold = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD); _reportFontLargeUnderline = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.UNDERLINE); gif.ScalePercent(35); document.AddTitle(_ReportObject.ReportTitle); document.SetPageSize(PageSize.LETTER); document.SetMargins(-50, -55, 10, 45); document.Open(); PrintReportHeader(table, gif); table.HeaderRows = 4; document.Add(table); table.TotalWidth = PageSize.LETTER.Width - 72; PrintReportDetail(table); if (table.Rows.Count > 0) { rowNumbers.Add(numberOfRows); PrintTotalSummaryRow(table); document.Add(table); } document.Close(); isSuccessful = true; } catch (DocumentException de) { _ReportObject.ReportError = de.Message; _ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { _ReportObject.ReportError = ioe.Message; _ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public bool CreateReport() { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER); try { //set up RunReport event overrides & create doc //ReportObject.ReportTempFile = "c:\\Program Files\\Phase2App\\logs\\"; ReportObject.CreateTemporaryFullName("PostAuditReport"); _pageCount = 1; PostAuditReport events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 120, document.PageSize.Height); float pageLeft = document.PageSize.Left; float pageright = document.PageSize.Right; columns.AddSimpleColumn(20, document.PageSize.Width - 20); //set up tables, etc... PdfPCell cell = new PdfPCell(); Image gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); document.Open(); document.SetPageSize(PageSize.LETTER); document.SetMargins(-100, -100, 10, 45); document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy")); PdfPTable tableInventoryTotalsCountedByStatus = new PdfPTable(6); tableInventoryTotalsCountedByStatus.WidthPercentage = 100;// document.PageSize.Width; SectionInventoryTotalsCountedByStatus(tableInventoryTotalsCountedByStatus, 6); columns.AddElement(tableInventoryTotalsCountedByStatus); PdfPTable tableChargeOff = new PdfPTable(9); tableChargeOff.WidthPercentage = 100;// document.PageSize.Width; WriteSections(tableChargeOff, 9, "Charge Off", (int)EnumPostAuditReportCategories.ChargeOff); columns.AddElement(tableChargeOff); PdfPTable tableReactivation = new PdfPTable(8); tableReactivation.WidthPercentage = 100;// document.PageSize.Width; WriteSections(tableReactivation, 8, "Reactivation", (int)EnumPostAuditReportCategories.Reactivation); columns.AddElement(tableReactivation); PdfPTable tableChargeOn = new PdfPTable(8); tableChargeOn.WidthPercentage = 100;// document.PageSize.Width; WriteSections(tableChargeOn, 8, "Charge On", (int)EnumPostAuditReportCategories.ChargeOn); columns.AddElement(tableChargeOn); PdfPTable tabletempRecon = new PdfPTable(4); tabletempRecon.WidthPercentage = 100;// document.PageSize.Width; WriteTempRecociliationSection(tabletempRecon, 4); columns.AddElement(tabletempRecon); PdfPTable tableFooter = new PdfPTable(3); tableFooter.WidthPercentage = 100;// document.PageSize.Width; WriteFooter(tableFooter, 3); columns.AddElement(tableFooter); document.Add(columns); document.Close(); //OpenFile(ReportObject.ReportTempFileFullName); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; //ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; //ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public bool CreateReport() { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate()); try { //set up RunReport event overrides & create doc TerminatedLayawayPickingSlip events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 90, document.PageSize.Height - (90)); float pageLeft = document.PageSize.Left; float pageright = document.PageSize.Right; columns.AddSimpleColumn(-27, document.PageSize.Width + 29); //set up tables, etc... PdfPTable table = new PdfPTable(7); table.WidthPercentage = 85;// document.PageSize.Width; PdfPCell cell = new PdfPCell(); Image gif = Image.GetInstance(Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new LayawayRunReports(); document.Open(); document.SetPageSize(PageSize.HALFLETTER.Rotate()); document.SetMargins(-100, -100, 10, 45); document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy")); //int layawayCount = ReportObject.TerminatedLayawayPickingSlipList.Count; //int counter = 1; //foreach (LayawayVO layaway in ReportObject.TerminatedLayawayPickingSlipList) //{ WriteCell(table, "Ticket #: " + ReportObject.TerminatedLayaway.TicketNumber.ToString(), ReportFontBold, 9, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); WriteInfo(table, ReportObject.TerminatedLayaway); DrawLine(table); WritePaymentList(table, ReportObject.TerminatedLayaway); DrawLine(table); WriteDetail(table, ReportObject.TerminatedLayaway); /*while (counter < layawayCount) * { * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * break; * } * counter++; * }*/ columns.AddElement(table); document.Add(columns); document.Close(); //OpenFile(); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
protected void Page_Load(object sender, EventArgs e) { int objetivoId = Convert.ToInt32(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var objetivo = Objetivo.ById(objetivoId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(objetivo.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Objetivo"], formatedDescription, DateTime.Now); string type = string.Empty; string origin = string.Empty; string originSufix = string.Empty; string reporterType = string.Empty; string reporter = string.Empty; string status = string.Empty; var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = objetivo.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Objetivo"].ToUpperInvariant() }; document.Open(); var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 15f, 30f, 15f, 30f }); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Name"], objetivo.Name, 3); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Responsible"], objetivo.Responsible.FullName, 3); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_DateStart"], objetivo.StartDate); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_ClosePreviewDate"], objetivo.PreviewEndDate); if (objetivo.VinculatedToIndicator) { var indicador = Indicador.ById(objetivo.IndicatorId.Value, companyId); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Indicator"], indicador.Description); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Periodicity"], indicador.Periodicity); } AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Description"], objetivo.Description, 4); AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Methodology"], objetivo.Methodology, 4); AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Resources"], objetivo.Resources, 4); AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Notes"], objetivo.Notes, 4); document.Add(table); if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { #region Acciones if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { var acciones = IncidentAction.ByObjetivoId(objetivoId, companyId); if (acciones.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableAcciones = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableAcciones.SetWidths(new float[] { 20f, 120f, 20f, 20f, 20f }); ToolsPdf.AddTableTitle(tableAcciones, dictionary["Item_Objetivo_ActionsReportTitle"]); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"])); int cont = 0; decimal totalAcciones = 0; foreach (var accion in acciones) { tableAcciones.AddCell(ToolsPdf.DataCell(accion.Status)); tableAcciones.AddCell(ToolsPdf.DataCell(accion.Description)); tableAcciones.AddCell(ToolsPdf.DataCell(accion.WhatHappenedOn)); tableAcciones.AddCell(ToolsPdf.DataCell(accion.ActionsOn)); tableAcciones.AddCell(ToolsPdf.DataCell(0)); cont++; var costs = IncidentActionCost.GetByIncidentActionId(accion.Id, company.Id); foreach (var cost in costs) { totalAcciones = cost.Amount; } } // TotalRow tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f, Colspan = 2 }); tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", totalAcciones), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableAcciones.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 3, Border = Rectangle.TOP_BORDER }); document.Add(tableAcciones); } } #endregion } #region Registros if (objetivo.VinculatedToIndicator) { var registros = IndicadorRegistro.ByIndicadorId(objetivo.IndicatorId.Value, companyId).ToList(); if (registros.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableRegistros = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableRegistros.SetWidths(new float[] { 20f, 20f, 120f, 40f, 50f }); ToolsPdf.AddTableTitle(tableRegistros, dictionary["Item_Objetivo_RecordsReportTitle"]); tableRegistros.AddCell(ToolsPdf.HeaderCell("*" + dictionary["Item_Indicador_TableRecords_Header_Value"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"])); int cont = 0; foreach (var registro in registros) { string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString(); // WEKE ALEX: con datacellmoney el dato debe ser decimal y lo poen con dos decimales tableRegistros.AddCell(ToolsPdf.DataCellMoney(registro.Value)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Date)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments)); tableRegistros.AddCell(ToolsPdf.DataCell(meta)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName)); cont++; } // TotalRow tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 3, Border = Rectangle.TOP_BORDER }); document.Add(tableRegistros); } } else { var registros = ObjetivoRegistro.GetByObjetivo(objetivoId, companyId).ToList(); if (registros.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableRegistros = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableRegistros.SetWidths(new float[] { 20f, 120f, 20f, 40f, 50f }); tableRegistros.AddCell(new PdfPCell(new Phrase(dictionary["Item_Objetivo_RecordsReportTitle"])) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Value"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"])); int cont = 0; foreach (var registro in registros) { string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString(); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Value)); tableRegistros.AddCell(ToolsPdf.DataCellCenter(registro.Date)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments)); tableRegistros.AddCell(ToolsPdf.DataCell(meta)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName)); cont++; } // TotalRow tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 3, Border = Rectangle.TOP_BORDER }); document.Add(tableRegistros); } } #endregion if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { #region Historico var historico = ObjetivoHistorico.ByObjetivoId(objetivoId); if (historico.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableHistorico = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableHistorico.SetWidths(new float[] { 20f, 20f, 120f, 50f }); ToolsPdf.AddTableTitle(tableHistorico, dictionary["Item_Objetivo_TabHistoric"]); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_Action"])); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IndicatorRecord_FieldLabel_Date"])); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_ObjetivoRecord_FieldLabel_Reason"])); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_CloseResponsible"])); int cont = 0; foreach (var objetivoHistorico in historico) { var actionText = string.Empty; var description = string.Empty; if (objetivoHistorico.Reason == "Restore") { actionText = dictionary["Item_ObjetivoHistorico_StatusRestore"]; } else { actionText = dictionary["Item_ObjetivoHistorico_StatusAnulate"]; description = objetivoHistorico.Reason; } tableHistorico.AddCell(ToolsPdf.DataCell(actionText)); tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Date)); tableHistorico.AddCell(ToolsPdf.DataCell(description)); tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Employee.FullName)); cont++; } // TotalRow tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableHistorico.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 2, Border = Rectangle.TOP_BORDER }); document.Add(tableHistorico); } #endregion } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
/// <summary> /// /// </summary> /// <param name="inputFile">The PDF file to split</param> /// <param name="splitStartPages"></param> public void SplitPDF(String inputFile, SortedList <int, String> splitStartPages) { if (!String.IsNullOrEmpty(inputFile) && !String.IsNullOrWhiteSpace(inputFile) && splitStartPages != null && splitStartPages.Count >= 2) { var inputDocument = new iTextSharpPDF.PdfReader(inputFile); // First split must begin with page 1 // Last split must not be higher than last page if (splitStartPages.Keys[0] == 1 && splitStartPages.Keys[splitStartPages.Count - 1] <= inputDocument.NumberOfPages) { int currentPage = 1; int firstPageOfSplit; int lastPageOfSplit; try { for (int splitPoint = 0; splitPoint <= (splitStartPages.Count - 1); splitPoint++) { firstPageOfSplit = currentPage; if (splitPoint < (splitStartPages.Count - 1)) { lastPageOfSplit = splitStartPages.Keys[splitPoint + 1] - 1; } else { lastPageOfSplit = inputDocument.NumberOfPages; } iTextSharpText.Document splitDocument = null; iTextSharpPDF.PdfCopy splitOutputFile = null; try { splitDocument = new iTextSharpText.Document(); splitOutputFile = new iTextSharpPDF.PdfCopy(splitDocument, new FileStream(splitStartPages.Values[splitPoint], FileMode.Create, FileAccess.ReadWrite)); splitDocument.Open(); for (int outputPage = firstPageOfSplit; outputPage <= lastPageOfSplit; outputPage++) { splitDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(currentPage)); splitOutputFile.AddPage(splitOutputFile.GetImportedPage(inputDocument, currentPage)); currentPage++; } } finally { if (splitDocument != null && splitDocument.IsOpen()) { splitDocument.Close(); } if (splitOutputFile != null) { splitOutputFile.Close(); splitOutputFile.FreeReader(inputDocument); } splitDocument = null; splitOutputFile = null; } } } catch { // Cleanup any files that may have // been written foreach (KeyValuePair <int, String> split in splitStartPages) { try { File.Delete(split.Value); } catch { } } throw; } finally { if (inputDocument != null) { inputDocument.Close(); } } } else { if (splitStartPages.Keys[splitStartPages.Count - 1] > inputDocument.NumberOfPages) { throw new ArgumentOutOfRangeException("splitStartPages", String.Format("Final page number must be less than the number of pages ({0}). Passed value is {1}.", inputDocument.NumberOfPages, splitStartPages.Keys[splitStartPages.Count - 1])); } throw new ArgumentOutOfRangeException("splitStartPages", "First page number must be 1."); } } else { if (inputFile == null) { throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString); } if (splitStartPages == null) { throw new ArgumentNullException("splitStartPages", exceptionArgumentNullOrEmptyString); } throw new ArgumentOutOfRangeException("splitStartPages", "Must contain at least two KeyValue pairs."); } }
public bool CreateReport() { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER); try { //set up RunReport event overrides & create doc //_pageCount = 1; RefurbList events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 90, document.PageSize.Height - (100)); columns.AddSimpleColumn(-5, document.PageSize.Width - 15); //set up tables, etc... int colspan = 12; var table = new PdfPTable(colspan); table.WidthPercentage = 95;// document.PageSize.Width; //table.TotalHeight = 95; var cell = new PdfPCell(); var gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new RunReport(); document.Open(); document.SetPageSize(PageSize.LETTER); document.SetMargins(-100, -20, 10, 35); document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy"))); ReportColumns(table, colspan, "Merchandise Expected to be Received from Refurb"); WriteDetail(table, colspan, ReportObject.ListRefurbItemsExpected); WriteTotals(table, colspan, ReportObject.ListRefurbItemsExpected); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); ReportColumns(table, colspan, "Merchandise Not Expected to be Received from Refurb"); WriteDetail(table, colspan, ReportObject.ListRefurbItemsNotExpected); WriteTotals(table, colspan, ReportObject.ListRefurbItemsNotExpected); WriteCell(table, string.Empty, ReportFont, colspan, Element.ALIGN_LEFT, Element.ALIGN_TOP, Rectangle.NO_BORDER); columns.AddElement(table); document.Add(columns); document.Close(); //OpenFile(ReportObject.ReportTempFileFullName); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public bool GenerateMCDSlipDocument() { storeNumber = GlobalDataAccessor.Instance.CurrentSiteId.StoreNumber; reportNumber = "CL-OP-68"; DataTable checkInfoDetails; string errorCode; string errorText; //Get the report data ShopProcedures.GetStoreManualCheckDepositData(GlobalDataAccessor.Instance.OracleDA, GlobalDataAccessor.Instance.CurrentSiteId.StoreId, ShopDateTime.Instance.ShopDate, out checkInfoDetails, out errorCode, out errorText); if (checkInfoDetails == null || checkInfoDetails.Rows.Count == 0) { FileLogger.Instance.logMessage(LogLevel.ERROR, this, "No data returned from stored procedure for manual check deposit slips " + errorText); return(false); } //Initialize fonts RptFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL); this.HeaderTitleFont = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10); this.MCDSlipReportTitle = @"Check Cash Deposit Slip"; document = new Document(PageSize.LETTER); document.AddTitle(MCDSlipReportTitle); PdfPTable table = new PdfPTable(8); rptFileName = SecurityAccessor.Instance.EncryptConfig.ClientConfig.GlobalConfiguration.BaseLogPath + "\\MCD" + DateTime.Now.ToString("MMddyyyyhhmmssFFFFFFF") + ".pdf"; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(rptFileName, FileMode.Create)); MCDPageEvents events = new MCDPageEvents(); writer.PageEvent = events; document.SetPageSize(PageSize.LETTER); document.SetMargins(0, 0, 10, 45); Image image = Image.GetInstance(Properties.Resources.logo, BaseColor.WHITE); image.ScalePercent(25); //Insert the report header InsertReportHeader(table, image); document.Open(); document.Add(table); PdfPTable newtable = new PdfPTable(4); //Insert the column headers InsertColumnHeaders(newtable); table.HeaderRows = 7; decimal totalCheckAmount = 0; int totalNumChecks = 0; foreach (DataRow dr in checkInfoDetails.Rows) { string makerName = Common.Libraries.Utility.Utilities.GetStringValue(dr["makername"]); string cdName = Utilities.GetStringValue(dr["username"]); decimal chkAmount = Utilities.GetDecimalValue(dr["checkamount"]); string depositDate = Utilities.GetDateTimeValue(dr["creationdate"]).FormatDate(); totalNumChecks++; totalCheckAmount += chkAmount; PdfPCell pCell = new PdfPCell(); pCell.Colspan = 1; pCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED; pCell.Border = Rectangle.NO_BORDER; pCell.Phrase = new Phrase(makerName, RptFont); newtable.AddCell(pCell); pCell.Phrase = new Phrase(cdName, RptFont); newtable.AddCell(pCell); pCell.Phrase = new Phrase(depositDate, RptFont); newtable.AddCell(pCell); pCell.Phrase = new Phrase(String.Format("{0:n}", chkAmount), RptFont); pCell.HorizontalAlignment = Element.ALIGN_RIGHT; newtable.AddCell(pCell); } //Add a blank line before summary newtable.AddCell(generateBlankLine(8)); //Insert summary table PdfPCell newCell = new PdfPCell(new Paragraph("", RptFont)); newCell.HorizontalAlignment = Element.ALIGN_LEFT; newCell.Border = Rectangle.TOP_BORDER; newCell.Colspan = 4; newtable.AddCell(newCell); newCell.Colspan = 1; newCell.HorizontalAlignment = Element.ALIGN_LEFT; newCell.Border = Rectangle.NO_BORDER; newCell.Phrase = new Phrase("Count of all Checks", RptFont); newtable.AddCell(newCell); newCell.Phrase = new Phrase(totalNumChecks.ToString(), RptFont); newtable.AddCell(newCell); newCell.Phrase = new Phrase("Total Amount of all Checks:", RptFont); newtable.AddCell(newCell); newCell.Phrase = new Phrase(string.Format("{0:n}", totalCheckAmount), RptFont); newCell.HorizontalAlignment = Element.ALIGN_RIGHT; newtable.AddCell(newCell); newCell = new PdfPCell(new Paragraph("", RptFont)); newCell.HorizontalAlignment = Element.ALIGN_LEFT; newCell.Border = Rectangle.BOTTOM_BORDER; newCell.Colspan = 4; newtable.AddCell(newCell); document.Add(newtable); //Insert report footer PdfPTable finalSummaryTable = new PdfPTable(8); finalSummaryTable.TotalWidth = 500f; InsertReportFooter(ref finalSummaryTable); float yAbsolutePosition = newtable.CalculateHeights(true); finalSummaryTable.WriteSelectedRows(0, -1, document.LeftMargin + 30, yAbsolutePosition + 30, writer.DirectContent); document.Close(); //Print and save the document PrintDocument(); return(true); }
public void PDFESTADOCERO() { Buscadores bus = new Buscadores(); vehiculo ovehiculo = bus.buscarvehiculo(txtpatente.Value); cliente ocliente = bus.ocliente(ovehiculo); modelo omarca = bus.buscarmodelo(ovehiculo); marca omodelo = bus.buscarmarca(omarca); iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4); var doc = new iTextSharp.text.Document(rec); rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive); doc.SetPageSize(iTextSharp.text.PageSize.A4); string path = Server.MapPath("~"); PdfWriter.GetInstance(doc, new FileStream(path + "/Presupuesto.pdf", FileMode.Create)); doc.Open(); //Cabecera BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GREEN.Darker()); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_LEFT; prgHeading.Add(new Chunk("Taller de Reparaciones - Presupuesto".ToUpper(), fntHead)); doc.Add(prgHeading); //Generado By Paragraph prgGeneratedBY = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLACK); prgGeneratedBY.Alignment = Element.ALIGN_RIGHT; prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor)); //Agregar LOG Empleado prgGeneratedBY.Add(new Chunk("\nFecha Generado valido por 5 dias : " + DateTime.Now.ToShortDateString(), fntAuthor)); prgGeneratedBY.Add(new Chunk("\nN° de Orden : " + OrdenActual.id_orden, fntAuthor)); doc.Add(prgGeneratedBY); //La f Linea Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); doc.Add(p); //Espacio doc.Add(new Chunk("\n", fntHead)); //Datos Paragraph Datos = new Paragraph(); BaseFont bfntDatos = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntDatos = new iTextSharp.text.Font(bfntDatos, 12, 0, iTextSharp.text.BaseColor.BLACK); Datos.Alignment = Element.ALIGN_CENTER; Datos.Add(new Chunk("Apellido y Nombre: " + ocliente.nombre + " DNI: " + ocliente.dni + " Telefono: " + ocliente.telefono + "\nCorreo Electronico: " + ocliente.email, fntDatos)); Datos.Add(new Chunk("\nPatente: " + ovehiculo.patente + " Modelo:" + omodelo.nombre + " Marca: " + omarca.nombre, fntDatos)); doc.Add(Datos); //Espacio doc.Add(new Chunk("\n", fntHead)); //Tabla PdfPTable table = new PdfPTable(dtable.Columns.Count); for (int i = 0; i < dtable.Columns.Count; i++) { string cellText = Server.HtmlDecode(dtable.Columns[i].ColumnName); PdfPCell cell = new PdfPCell(); cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000")))); cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8")); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingBottom = 5; table.AddCell(cell); } //Agregando Campos a la tabla for (int i = 0; i < dtable.Rows.Count; i++) { for (int j = 0; j < dtable.Columns.Count; j++) { table.AddCell(dtable.Rows[i][j].ToString()); } } doc.Add(table); //Espacio doc.Add(new Chunk("\n", fntHead)); //Datos2.0 Paragraph Datos2 = new Paragraph(); Datos2.Alignment = Element.ALIGN_RIGHT; Datos2.Add(new Chunk("\nPrecio Total= $" + lblprecio.Text, fntDatos)); doc.Add(Datos2); Paragraph Datos3 = new Paragraph(); Datos3.Alignment = Element.ALIGN_CENTER; iTextSharp.text.Font fntDatos3 = new iTextSharp.text.Font(bfntDatos, 12, 1, iTextSharp.text.BaseColor.BLACK); Datos3.Add(new Chunk("\nPresupuesto NO VALIDO como Factura", fntDatos3)); doc.Add(Datos3); doc.Close(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('Presupuesto.pdf','_newtab');", true); }
protected void PDFLST(object sender, EventArgs e) { Buscadores bus = new Buscadores(); List <stock> Lstock = bus.listastock(); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Codigo"), new DataColumn("Detalle"), new DataColumn("Marca"), new DataColumn("Cantidad") }); foreach (stock ostock in Lstock) { dt.Rows.Add(ostock.codigo, ostock.detalle, ostock.marca, ostock.cantidad); } iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4); var doc = new iTextSharp.text.Document(rec); rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive); doc.SetPageSize(iTextSharp.text.PageSize.A4); string path = Server.MapPath("~"); PdfWriter.GetInstance(doc, new FileStream(path + "/ReportesLST.pdf", FileMode.Create)); doc.Open(); //Cabecera BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GREEN.Darker()); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_LEFT; prgHeading.Add(new Chunk("Taller de Reparaciones Reportes PDF".ToUpper(), fntHead)); doc.Add(prgHeading); //Generado By Paragraph prgGeneratedBY = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLACK); prgGeneratedBY.Alignment = Element.ALIGN_RIGHT; prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor)); //Agregar LOG Empleado prgGeneratedBY.Add(new Chunk("\nFecha Generada : " + DateTime.Now.ToShortDateString(), fntAuthor)); doc.Add(prgGeneratedBY); //La f Linea Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); doc.Add(p); //Espacio doc.Add(new Chunk("\n", fntHead)); //Tabla PdfPTable table = new PdfPTable(dt.Columns.Count); for (int i = 0; i < dt.Columns.Count; i++) { string cellText = Server.HtmlDecode(dt.Columns[i].ColumnName); PdfPCell cell = new PdfPCell(); cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000")))); cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8")); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingBottom = 5; table.AddCell(cell); } //Agregando Campos a la tabla for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table.AddCell(dt.Rows[i][j].ToString()); } } doc.Add(table); doc.Close(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('ReportesLST.pdf','_newtab');", true); }
public bool CreateReport() { bool isSuccessful = false; _document = new iTextSharp.text.Document(PageSize.LEGAL); try { //set up RunReport event overrides & create doc _ReportObject = new ReportObject(); _ReportObject.CreateTemporaryFullName(); if (!Directory.Exists(_logPath)) { Directory.CreateDirectory(_logPath); } reportFileName = _logPath + "\\" + _ReportObject.ReportTempFileFullName; PdfWriter writer = PdfWriter.GetInstance(_document, new FileStream(reportFileName, FileMode.Create)); //writer.PageEvent = this; //set up tables, etc... int columns = 6; PdfPTable table = new PdfPTable(columns); Image gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); // Image gif = Image.GetInstance(PawnReportResources.calogo, BaseColor.WHITE); _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL); _reportFontLargeBold = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD); gif.ScalePercent(35); //gif.ScalePercent(75); _document.AddTitle(_reportTitle); _document.SetPageSize(PageSize.LETTER); _document.SetMargins(-50, -55, 10, 45); writer.PageEvent = this; _document.Open(); //Go ahead and open the document so tables can be added. //PrintReportHeader(table, gif, columns); PrintReportHeader(gif); PrintReportDetail(); if (!_catcoTransferType.Equals("Appraisal", StringComparison.CurrentCultureIgnoreCase) && !_catcoTransferType.Equals("Wholesale", StringComparison.CurrentCultureIgnoreCase)) { PopulateMetalTypes(); AggregateData(); PrintTotalSummaryRow(table, writer); } table.HeaderRows = 3; _document.Add(table); _document.Close(); //OpenFile(reportFileName); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { _ReportObject.ReportError = de.Message; _ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { _ReportObject.ReportError = ioe.Message; _ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
protected void Page_Load(object sender, EventArgs e) { var learningId = Convert.ToInt32(Request.QueryString["id"]); var companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary<string, string>; var learning = new Learning(learningId, companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(learning.Description); var fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Learning"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = learning.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Learning"] }; writer.PageEvent = pageEventHandler; var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER; document.Open(); #region Dades bàsiques // Ficha pincipal var table = new PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 30f, 30f, 30f, 30f, 30f }); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Course"])); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Description, descriptionFont)) { Border = 0, BackgroundColor = new iTS.BaseColor(255, 255, 255), Padding = 6f, PaddingTop = 4f, HorizontalAlignment = Rectangle.ALIGN_LEFT, Colspan = 5 }); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EstimatedDate"])); table.AddCell(ToolsPdf.DataCell(learning.DateEstimated, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Hours"])); table.AddCell(ToolsPdf.DataCell(learning.Hours, descriptionFont)); string statusText = string.Empty; switch (learning.Status) { case 1: statusText = dictionary["Item_Learning_Status_Started"]; break; case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break; case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break; default: statusText = dictionary["Item_Learning_Status_InProgress"]; break; } table.AddCell(TitleLabel(dictionary["Item_Learning_ListHeader_Status"])); table.AddCell(ToolsPdf.DataCell(statusText, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_StartDate"])); table.AddCell(ToolsPdf.DataCell(learning.RealStart, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EndDate"])); table.AddCell(ToolsPdf.DataCell(learning.RealFinish, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Amount"])); table.AddCell(ToolsPdf.DataCellMoney(learning.Amount, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Coach"])); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Master, descriptionFont)) { Border = 0, BackgroundColor = new iTS.BaseColor(255, 255, 255), Padding = 6f, PaddingTop = 4f, HorizontalAlignment = Rectangle.ALIGN_LEFT, Colspan = 5 }); // Objective table.AddCell(SeparationRow()); table.AddCell(TitleAreaCell(dictionary["Item_Learning_Objetive"])); table.AddCell(TextAreaCell(Environment.NewLine + learning.Objective, borderSides, Rectangle.ALIGN_LEFT, 6)); // Methodology table.AddCell(SeparationRow()); table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Methodology"])); table.AddCell(TextAreaCell(Environment.NewLine + learning.Methodology, borderSides, Rectangle.ALIGN_LEFT, 6)); // Notes table.AddCell(SeparationRow()); table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + learning.Notes, borderSides, Rectangle.ALIGN_LEFT, 6)); document.Add(table); #endregion #region Asistentes var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableAssistants = new iTSpdf.PdfPTable(3) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableAssistants.SetWidths(new float[] { 90f, 20f, 20f }); tableAssistants.AddCell(new PdfPCell(new Phrase(learning.Description, descriptionFont)) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistants"])); tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Done"])); tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Evaluated"])); int cont = 0; bool pair = false; var times = new iTS.Font(arial, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK); var timesBold = new iTS.Font(arial, 8, iTS.Font.BOLD, iTS.BaseColor.BLACK); learning.ObtainAssistance(); foreach (var assistance in learning.Assistance) { int border = 0; var lineBackground = pair ? rowEven : rowPair; tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(assistance.Employee.FullName, times)) { Border = border, BackgroundColor = lineBackground, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell }); string completedText = string.Empty; if (assistance.Completed.HasValue) { completedText = assistance.Completed.Value ? dictionary["Common_Yes"] : dictionary["Common_No"]; } tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(completedText, times)) { Border = border, BackgroundColor = lineBackground, HorizontalAlignment = Element.ALIGN_CENTER, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell }); string successText = string.Empty; if (assistance.Success.HasValue) { successText = assistance.Success.Value ? dictionary["Common_Yes"] : dictionary["Common_No"]; } tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(successText, times)) { Border = border, BackgroundColor = lineBackground, HorizontalAlignment = Element.ALIGN_CENTER, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell }); cont++; } // TotalRow if(learning.Assistance.Count == 0) { tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_LearningList_NoAssistants"], descriptionFont)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell, Colspan = 3, HorizontalAlignment = Rectangle.ALIGN_CENTER }); } tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont), times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell, Colspan = 3 }); document.Add(tableAssistants); #endregion document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
/// <summary> /// Takes pages from two pdf files, and produces an output file /// whose odd pages are the contents of the first, and /// even pages are the contents of the second. Useful for /// merging front/back output from single sided scanners. /// </summary> /// <param name="oddPageFile">The file supplying odd numbered pages</param> /// <param name="evenPageFile">The file supplying even numbered pages</param> /// <param name="outputFile">The output file containing the merged pages</param> /// <param name="skipExtraPages">Set to true to skip any extra pages if /// one file is longer than the other</param> public void EvenOddMerge(String oddPageFile, String evenPageFile, String outputFile, bool skipExtraPages) { if (!String.IsNullOrEmpty(oddPageFile) && !String.IsNullOrWhiteSpace(oddPageFile) && !String.IsNullOrEmpty(evenPageFile) && !String.IsNullOrWhiteSpace(evenPageFile) && !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile)) { var oddPageDocument = new iTextSharpPDF.PdfReader(oddPageFile); var evenPageDocument = new iTextSharpPDF.PdfReader(evenPageFile); try { iTextSharpText.Document mergedOutputDocument = null; iTextSharpPDF.PdfCopy mergedOutputFile = null; int lastPage = 0; switch (skipExtraPages) { case (false): lastPage = oddPageDocument.NumberOfPages; if (evenPageDocument.NumberOfPages > oddPageDocument.NumberOfPages) { lastPage = evenPageDocument.NumberOfPages; } else { lastPage = oddPageDocument.NumberOfPages; } break; case (true): if (evenPageDocument.NumberOfPages < oddPageDocument.NumberOfPages) { lastPage = evenPageDocument.NumberOfPages; } else { lastPage = oddPageDocument.NumberOfPages; } break; } try { mergedOutputDocument = new iTextSharpText.Document(); mergedOutputFile = new iTextSharpPDF.PdfCopy(mergedOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); mergedOutputDocument.Open(); for (int loop = 1; loop <= lastPage; loop++) { // Extract and merge odd page if (loop <= oddPageDocument.NumberOfPages) { mergedOutputDocument.SetPageSize(oddPageDocument.GetPageSizeWithRotation(loop)); mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(oddPageDocument, loop)); } // Extract and merge even page if (loop <= evenPageDocument.NumberOfPages) { mergedOutputDocument.SetPageSize(evenPageDocument.GetPageSizeWithRotation(loop)); mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(evenPageDocument, loop)); } } } finally { if (mergedOutputDocument != null && mergedOutputDocument.IsOpen()) { mergedOutputDocument.Close(); } if (mergedOutputFile != null) { mergedOutputFile.Close(); mergedOutputFile.FreeReader(oddPageDocument); mergedOutputFile.FreeReader(evenPageDocument); } } } catch { try { File.Delete(outputFile); } catch { } throw; } finally { try { if (oddPageDocument != null) { oddPageDocument.Close(); } oddPageDocument = null; } catch { } try { if (evenPageDocument != null) { evenPageDocument.Close(); } evenPageDocument = null; } catch { } } } else { if (String.IsNullOrEmpty(oddPageFile) || String.IsNullOrWhiteSpace(oddPageFile)) { throw new ArgumentNullException("oddPageFile", exceptionArgumentNullOrEmptyString); } if (String.IsNullOrEmpty(evenPageFile) || String.IsNullOrWhiteSpace(evenPageFile)) { throw new ArgumentNullException("evenPageFile", exceptionArgumentNullOrEmptyString); } if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile)) { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } } }
/// <summary> /// Extracts a range of pages from a PDF file, /// and writes them to a new file. /// </summary> /// <param name="inputFile">The PDF to extract pages from.</param> /// <param name="outputFile">The new file to write the extracted pages to.</param> /// <param name="firstPage">The first page to extract.</param> /// <param name="lastPage">The last page to extract.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <remarks><see cref="FileStream"/> constructor exceptions may also be thrown.</remarks> public void ExtractPDFPages(String inputFile, String outputFile, int firstPage, int lastPage) { if (!String.IsNullOrEmpty(inputFile) && !String.IsNullOrWhiteSpace(inputFile) && !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile) && firstPage > 0 && lastPage > 0 && lastPage >= firstPage) { var inputDocument = new iTextSharpPDF.PdfReader(inputFile); try { // Page numbers specified must not be greater // than the number of pages in the document if (firstPage <= inputDocument.NumberOfPages && lastPage <= inputDocument.NumberOfPages) { iTextSharpText.Document extractOutputDocument = null; iTextSharpPDF.PdfCopy extractOutputFile = null; try { extractOutputDocument = new iTextSharpText.Document(); extractOutputFile = new iTextSharpPDF.PdfCopy(extractOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); extractOutputDocument.Open(); for (int loop = firstPage; loop <= lastPage; loop++) { extractOutputDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(loop)); extractOutputFile.AddPage(extractOutputFile.GetImportedPage(inputDocument, loop)); } } finally { if (extractOutputDocument != null && extractOutputDocument.IsOpen()) { extractOutputDocument.Close(); } if (extractOutputFile != null) { extractOutputFile.Close(); extractOutputFile.FreeReader(inputDocument); } } } else { if (firstPage > inputDocument.NumberOfPages) { throw new ArgumentOutOfRangeException("firstPage", String.Format(exceptionParameterCannotBeGreaterThan, "firstPage", "the number of pages in the document.")); } throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeGreaterThan, "firstPage", "the number of pages in the document.")); } } catch { try { File.Delete(outputFile); } catch { } throw; } finally { if (inputDocument != null) { inputDocument.Close(); } inputDocument = null; } } else { if (String.IsNullOrEmpty(inputFile) || String.IsNullOrWhiteSpace(inputFile)) { throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString); } if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile)) { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } if (firstPage < 1) { throw new ArgumentOutOfRangeException("firstPage", exceptionArgumentZeroOrNegative); } if (lastPage < 1) { throw new ArgumentOutOfRangeException("lastPage", exceptionArgumentZeroOrNegative); } if (lastPage < firstPage) { throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeLessThan, "lastPage", "firstPage")); } } }
//create report public bool CreateReport()//ReportObject rptObj) { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL); try { //set up RunReport event overrides & create doc GunAuditReport events = new GunAuditReport(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; //set up tables, etc... PdfPTable table = new PdfPTable(21); PdfPCell cell = new PdfPCell(); Image gif = Image.GetInstance(Resources.logo, BaseColor.WHITE); _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL); _reportFontLargeBold = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD); _reportFontLargeUnderline = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.UNDERLINE); gif.ScalePercent(35); runReport = new RunReport(); if (reportObject.ReportDetail.Equals("Summary")) { document.AddTitle(reportObject.ReportTitle + " - Summary: " + DateTime.Now.ToString("MM/dd/yyyy")); document.SetPageSize(PageSize.LETTER); document.SetMargins(-50, -55, 10, 45); SummaryReportHeader(table, gif); Int32[,] gunStatus; gunStatus = new Int32[6, 4]; SummaryReportDetail(table, out gunStatus, false); SummaryReportSummary(table, gunStatus, false); table.HeaderRows = 10; } else//detail version { document.AddTitle(reportObject.ReportTitle + " - Detailed: " + DateTime.Now.ToString("MM/dd/yyyy")); document.SetPageSize(PageSize.LEGAL.Rotate()); document.SetMargins(-100, -100, 10, 45); DetailReportHeader(table, gif); DetailColumnHeaders(table); DetailReportDetail(table); DetailReportSummary(table);//calls summary methods table.HeaderRows = 7; } document.Open(); document.Add(table); document.Close(); isSuccessful = true; } catch (DocumentException de) { reportObject.ReportError = de.Message;; reportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { reportObject.ReportError = ioe.Message;; reportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
protected void Page_Load(object sender, EventArgs e) { var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER; var borderBL = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderBR = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var borderTBL = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderTBR = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var alignRight = Element.ALIGN_RIGHT; long oportunityId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var oportunity = Oportunity.ById(oportunityId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(oportunity.Description); var alignLeft = Element.ALIGN_LEFT; string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Oportunity"], formatedDescription, DateTime.Now); var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = oportunity.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Oportunity"] }; writer.PageEvent = pageEventHandler; document.Open(); #region Dades bàsiques var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 50f, 30f, 50f }); table.AddCell(new PdfPCell(new Phrase(oportunity.Description, descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 10f, PaddingBottom = 10f, HorizontalAlignment = Element.ALIGN_CENTER }); table.AddCell(TitleCell(dictionary["Item_BusinessRisk_Tab_Basic"], 4)); table.AddCell(TitleLabel(dictionary["Item_BusinessRisk_LabelField_DateStart"])); table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", oportunity.DateStart))); table.AddCell(TitleLabel(dictionary["Item_Process"])); table.AddCell(TitleData(oportunity.Process.Description)); table.AddCell(TitleLabel(dictionary["Item_Rule"])); table.AddCell(TitleData(oportunity.Rule.Description)); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"])); table.AddCell(TitleData(oportunity.Rule.Limit.ToString())); string costText = oportunity.Cost.ToString(); if (costText == "0") { costText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"])); table.AddCell(TitleData(costText)); string impactText = oportunity.Impact.ToString(); if (impactText == "0") { impactText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"])); table.AddCell(TitleData(impactText)); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"])); table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"])); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Description"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Description, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Causes"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Causes, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Control"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Control, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Notes, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_Tab_Graphics"], 4)); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"])); table.AddCell(TitleData(oportunity.Rule.Limit.ToString())); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"])); table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"])); string finalCostText = oportunity.FinalCost.ToString(); if (finalCostText == "0") { finalCostText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"])); table.AddCell(TitleData(finalCostText)); string finalImpactText = oportunity.FinalImpact.ToString(); if (finalImpactText == "0") { finalImpactText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"])); table.AddCell(TitleData(finalImpactText)); document.Add(table); #endregion if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { // Añadir posible acción var action = IncidentAction.ByOportunityId(oportunity.Id, companyId); if (action.Id > 0) { var tableAction = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f }); // Descripción var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK); tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont)) { Colspan = 4, Border = ToolsPdf.BorderBottom, HorizontalAlignment = Rectangle.ALIGN_CENTER }); tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER)); tableAction.AddCell(ValueCell(action.Description, ToolsPdf.BorderNone, alignLeft, 3)); // WhatHappend tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow()); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2)); // Causes var causesFullName = string.Empty; var causesDate = string.Empty; if (action.CausesBy != null) { causesFullName = action.CausesBy.FullName; causesDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn); } tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow()); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2)); // Actions var actionFullName = string.Empty; var actionDate = string.Empty; if (action.ActionsBy != null) { actionFullName = action.ActionsBy.FullName; actionDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn); } tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow()); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2)); // Monitoring tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4)); // Close var closedFullName = string.Empty; var closedDate = string.Empty; if (action.ClosedBy != null) { closedFullName = action.ClosedBy.FullName; closedDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn); } tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"])); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2)); // Notes tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4)); document.NewPage(); document.Add(tableAction); } #region Historico acciones var historico = IncidentAction.ByOportunityCode(oportunity.Code, company.Id).Where(ia => ia.Oportunity.Id != oportunity.Id).OrderBy(incidentAction => incidentAction.WhatHappenedOn).ToList(); if (historico.Count > 0) { var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableHistoric = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableHistoric.SetWidths(new float[] { 20f, 30f, 120f, 20f, 20f }); tableHistoric.AddCell(new PdfPCell(new Phrase(dictionary["Item_BusinessRisk_Tab_HistoryActions"], descriptionFont)) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"])); int cont = 0; foreach (var accion in historico) { string statusText = dictionary["Item_Incident_Status1"]; if (accion.CausesOn.HasValue) { statusText = dictionary["Item_Incident_Status2"]; } if (accion.ActionsOn.HasValue) { statusText = dictionary["Item_Incident_Status3"]; } if (accion.ClosedOn.HasValue) { statusText = dictionary["Item_Incident_Status4"]; } tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.WhatHappenedOn, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCell(statusText, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCell(accion.Description, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ActionsOn, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ClosedOn, ToolsPdf.LayoutFonts.Times)); cont++; } tableHistoric.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 5, Padding = 8f }); document.Add(tableHistoric); } #endregion #region Costes var costs = IncidentActionCost.ByOportunityId(oportunity.Id, company.Id); if (costs.Count > 0) { var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableCost = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableCost.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f }); tableCost.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_Tab_Costs"], descriptionFont)) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"])); int cont = 0; decimal costTotal = 0; foreach (var cost in costs) { tableCost.AddCell(ToolsPdf.DataCell(cost.Description, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount * cost.Quantity, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCell(cost.Responsible.FullName, ToolsPdf.LayoutFonts.Times)); costTotal += cost.Amount * cost.Quantity; cont++; } tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 2, Padding = 8f }); tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 1, Padding = 8f, HorizontalAlignment = alignRight }); tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(costTotal), ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 1, Padding = 8f, HorizontalAlignment = alignRight }); tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 1, Padding = 8f, HorizontalAlignment = alignRight }); document.Add(tableCost); } #endregion } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public static void CreatePago_Especialsta_Report(string monto1, string fechaInicio1, string fechaFin1, string usuarioMedico1, int usuarioPaga1, List <string> ids1, string ruta, string filePDF, organizationDto infoEmpresa) { Document document = new Document(PageSize.A5, 15f, 15f, 15f, 40f); document.SetPageSize(iTextSharp.text.PageSize.A5); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePDF, FileMode.Create)); pdfPage page = new pdfPage(); writer.PageEvent = page; document.Open(); #region Declaration Tables var subTitleBackGroundColor = new BaseColor(System.Drawing.Color.Gray); string include = string.Empty; List <PdfPCell> cells = null; float[] columnWidths = null; string[] columnValues = null; string[] columnHeaders = null; PdfPTable header2 = new PdfPTable(6); header2.HorizontalAlignment = Element.ALIGN_CENTER; header2.WidthPercentage = 100; float[] widths1 = new float[] { 16.6f, 18.6f, 16.6f, 16.6f, 16.6f, 16.6f }; header2.SetWidths(widths1); PdfPTable companyData = new PdfPTable(6); companyData.HorizontalAlignment = Element.ALIGN_CENTER; companyData.WidthPercentage = 100; float[] widthscolumnsCompanyData = new float[] { 16.6f, 16.6f, 16.6f, 16.6f, 16.6f, 16.6f }; companyData.SetWidths(widthscolumnsCompanyData); PdfPTable filiationWorker = new PdfPTable(4); PdfPTable table = null; PdfPCell cell = null; document.Add(new Paragraph("\r\n")); #endregion #region Fonts Font fontTitle1 = FontFactory.GetFont("Calibri", 10, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontTitle2 = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black)); Font fontTitleTable = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontTitleTableNegro = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontSubTitle = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.White)); Font fontSubTitleNegroNegrita = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontColumnValue = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black)); Font fontColumnValueBold = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontColumnValueApendice = FontFactory.GetFont("Calibri", 5, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontTitleTableAntecedentesOcupacionales = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black)); Font fontColumnValueAntecedentesOcupacionales = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black)); #endregion var tamaño_celda = 18f; var tamaño_celda2 = 60f; #region Conexion Sigesoft ConexionSigesoft conectaSigesoft = new ConexionSigesoft(); conectaSigesoft.opensigesoft(); #endregion #region Fecha string anioinicio = fechaInicio1.Substring(6, 4); string mesinicio = fechaInicio1.Substring(3, 2); string diainicio = fechaInicio1.Substring(0, 2); DateTime localDate = DateTime.Now; #endregion #region Title var fechain = fechaInicio1.Split(' '); var fechafin = fechaFin1.Split(' '); var rutaImg = GetApplicationConfigValue("Logo"); var imageLogo = new PdfPCell(GetImageLogo(rutaImg.ToString(), null, null, 120, 50)) { HorizontalAlignment = PdfPCell.ALIGN_CENTER }; #region Obtener usuarios var cadena1 = "select PP.v_FirstName+' '+PP.v_FirstLastName+' '+PP.v_SecondLastName, v_UserName from systemuser SU " + "Inner join person PP " + "On SU.v_PersonId=PP.v_PersonId " + "where i_SystemUserId=" + usuarioPaga1; SqlCommand comando1 = new SqlCommand(cadena1, connection: conectaSigesoft.conectarsigesoft); SqlDataReader lector1 = comando1.ExecuteReader(); String cajanombre = "", cajauser = ""; while (lector1.Read()) { cajanombre = lector1.GetValue(0).ToString(); cajauser = lector1.GetValue(1).ToString(); } lector1.Close(); #endregion cells = new List <PdfPCell>() { new PdfPCell(imageLogo) { Rowspan = 1, HorizontalAlignment = PdfPCell.ALIGN_CENTER, MinimumHeight = tamaño_celda2, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE }, new PdfPCell(new Phrase("PAGO MÉDICO ESPECIALISTA ", fontTitle1)) { Rowspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda2, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE }, new PdfPCell(new Phrase(" usuario: " + cajauser + "\r\n Desde: " + fechain[0] + "\r\n Hasta: " + fechafin[0], fontColumnValueBold)) { Rowspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda2, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE }, }; columnWidths = new float[] { 35f, 35f, 30f }; filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTableNegro, null); document.Add(filiationWorker); #endregion #region Cabecera cells = new List <PdfPCell>() { new PdfPCell(new Phrase("Nombre del Paciente", fontColumnValueBold)) { BackgroundColor = BaseColor.LIGHT_GRAY, Rowspan = 1, HorizontalAlignment = PdfPCell.ALIGN_CENTER, MinimumHeight = tamaño_celda, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }, new PdfPCell(new Phrase("Protocolo de Atención", fontColumnValueBold)) { BackgroundColor = BaseColor.LIGHT_GRAY, Rowspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda }, new PdfPCell(new Phrase("Fecha", fontColumnValueBold)) { BackgroundColor = BaseColor.LIGHT_GRAY, Rowspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda }, }; columnWidths = new float[] { 42f, 42f, 15f }; filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTableNegro, null); document.Add(filiationWorker); #endregion #region Detalle foreach (var serviceId in ids1) { var ids = serviceId.Split('|'); foreach (var id in ids) { var r = id; #region Query var cadena = "Select PP.v_FirstName+', '+PP.v_FirstLastName+' '+PP.v_SecondLastName as Persona, " + "PR.v_Name as Protocolo, d_ServiceDate as Fecha " + "from service SR " + "Inner Join person PP " + " On SR.v_PersonId = PP.v_PersonId " + "Inner Join protocol PR " + "On SR.v_ProtocolId = PR.v_ProtocolId " + "where SR.v_ServiceId='" + id + "'"; #endregion #region Lector Open SqlCommand comando = new SqlCommand(cadena, connection: conectaSigesoft.conectarsigesoft); SqlDataReader lector = comando.ExecuteReader(); #endregion #region Llenar Detalle while (lector.Read()) { var fecha = lector.GetValue(2).ToString().Split(' '); cells = new List <PdfPCell>() { new PdfPCell(new Phrase(lector.GetValue(0).ToString(), fontColumnValue)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase(lector.GetValue(1).ToString(), fontColumnValue)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase(fecha[0].ToString(), fontColumnValue)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, }; columnWidths = new float[] { 42f, 42f, 15f }; filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTableNegro, null); document.Add(filiationWorker); } lector.Close(); #endregion } } #endregion #region Recibido cells = new List <PdfPCell>() { new PdfPCell(new Phrase("Documento emitido por:", fontColumnValueBold)) { BackgroundColor = BaseColor.LIGHT_GRAY, Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase("Dr(a) Especialista", fontColumnValueBold)) { BackgroundColor = BaseColor.LIGHT_GRAY, Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase("Monto a pagar:", fontColumnValueBold)) { BackgroundColor = BaseColor.LIGHT_GRAY, Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase(cajanombre, fontColumnValueBold)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase(usuarioMedico1, fontColumnValueBold)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase(monto1, fontColumnValueBold)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase("Firma Emisor:", fontColumnValue)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda2, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase("Recibi conforme:", fontColumnValue)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda2, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, new PdfPCell(new Phrase("Fecha y hora" + "\rde Impresión: \r" + localDate, fontColumnValue)) { Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda2, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.BLACK }, }; columnWidths = new float[] { 42f, 42f, 15f }; filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTableNegro, null); document.Add(filiationWorker); #endregion document.Close(); writer.Close(); writer.Dispose(); RunFile(filePDF); }
protected void Page_Load(object sender, EventArgs e) { long auditoryId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var auditory = Auditory.ById(auditoryId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } string formatedDescription = auditory.Description.Replace("?", string.Empty); formatedDescription = formatedDescription.Replace("#", string.Empty); formatedDescription = formatedDescription.Replace("/", string.Empty); formatedDescription = formatedDescription.Replace("\\", string.Empty); formatedDescription = formatedDescription.Replace(":", string.Empty); formatedDescription = formatedDescription.Replace(";", string.Empty); formatedDescription = formatedDescription.Replace(".", string.Empty); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Auditory"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = auditory.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Auditory"] }; writer.PageEvent = pageEventHandler; document.Open(); #region Dades bàsiques // Ficha pincipal var planning = AuditoryPlanning.ByAuditory(auditory.Id, auditory.CompanyId); var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 50f, 30f, 50f }); table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"])); table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()])); if (auditory.Provider.Id > 0) { table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"])); table.AddCell(TitleData(auditory.Provider.Description)); } else if (auditory.Customer.Id > 0) { table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"])); table.AddCell(TitleData(auditory.Customer.Description)); } else { table.AddCell(TitleData(string.Empty, 2)); } table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"])); var rulesText = string.Empty; bool firstRule = true; foreach (var rule in auditory.Rules) { if (firstRule) { firstRule = false; } else { rulesText += ", "; } rulesText += rule.Description; } table.AddCell(TitleData(rulesText, 3)); var previewDateText = string.Empty; if (planning != null && planning.Count > 0) { previewDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", planning.OrderBy(p => p.Date).First().Date); } table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"])); table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3)); //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"])); //table.AddCell(TitleData(previewDateText)); table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"])); if (auditory.PlannedBy.Id > 0) { var planningText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.PlannedBy.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"); table.AddCell(TitleData(planningText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"])); if (auditory.ClosedBy.Employee.Id > 0) { var closedText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.ClosedBy.Employee.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"); table.AddCell(TitleData(closedText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"])); if (auditory.ValidatedBy.Id > 0) { var validatedText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.ValidatedBy.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"); table.AddCell(TitleData(validatedText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Scope"])); table.AddCell(TitleData(auditory.Scope, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"])); table.AddCell(TitleData(auditory.EnterpriseAddress, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"])); table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3)); document.Add(table); #endregion if (auditory.Status > 2) { var widthsPlanning = new float[] { 30f, 20f, 25f, 60f, 60f, 60f }; var tablePlanning = new PdfPTable(widthsPlanning.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tablePlanning.SetWidths(widthsPlanning); tablePlanning.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_PlanningTable_Title"], descriptionFont)) { Colspan = 6, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Date"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Hour"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Duration"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Process"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Auditor"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Audited"])); foreach (var pla in planning) { var hourText = string.Empty; var hours = 0; var minutes = pla.Hour; while (minutes > 59) { hours++; minutes -= 60; } hourText = string.Format(CultureInfo.InvariantCulture, "{0:0}:{1:00}", hours, minutes); var auditedText = pla.ProviderName; if (string.IsNullOrEmpty(auditedText)) { auditedText = pla.Audited.FullName; } tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Date)); tablePlanning.AddCell(ToolsPdf.DataCellCenter(hourText)); tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Duration)); tablePlanning.AddCell(ToolsPdf.DataCell(pla.Process.Description)); tablePlanning.AddCell(ToolsPdf.DataCell(pla.Auditor.Description)); tablePlanning.AddCell(ToolsPdf.DataCell(auditedText)); } document.Add(tablePlanning); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var widthsTroballes = new float[] { 30f, 30f, 20f, 8f }; var tableTroballes = new PdfPTable(widthsTroballes.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableTroballes.SetWidths(widthsTroballes); tableTroballes.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Found"], descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Found"])); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Requirement"])); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Result"])); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"])); var troballes = AuditoryCuestionarioFound.ByAuditory(auditory.Id, auditory.CompanyId); foreach (var troballa in troballes) { tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Text)); tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Requeriment)); tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Unconformity)); tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Action ? dictionary["Common_Yes"] : dictionary["Common_No"])); } document.Add(tableTroballes); var widthsMillores = new float[] { 80f, 8f }; var tableMillores = new PdfPTable(widthsMillores.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableMillores.SetWidths(widthsMillores); tableMillores.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Improvements"], descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Improvement"])); tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"])); var millores = AuditoryCuestionarioImprovement.ByAuditory(auditory.Id, auditory.CompanyId); foreach (var millora in millores) { tableMillores.AddCell(ToolsPdf.DataCell(millora.Text)); tableMillores.AddCell(ToolsPdf.DataCell(millora.Action ? dictionary["Common_Yes"] : dictionary["Common_No"])); } document.Add(tableMillores); if (!string.IsNullOrEmpty(auditory.PuntosFuertes.Trim())) { document.Add(new Phrase(Environment.NewLine)); document.Add(new Phrase(dictionary["Item_Auditory_Label_PuntosFuertes"], new Font(this.arial, 10, Font.BOLD, BaseColor.BLACK))); document.Add(new Phrase(Environment.NewLine)); document.Add(new Phrase(auditory.PuntosFuertes)); } var actions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId); if (actions != null && actions.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var widthsActions = new float[] { 8f, 80f }; var tableActions = new PdfPTable(widthsActions.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableActions.SetWidths(widthsActions); tableActions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"])); tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"])); foreach (var action in actions) { string actionTypeText = string.Empty; switch (action.ActionType) { default: case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break; case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break; case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break; } tableActions.AddCell(ToolsPdf.DataCell(actionTypeText)); tableActions.AddCell(ToolsPdf.DataCell(action.Description)); } document.Add(tableActions); } } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public bool CreateReport(DataTable dt) { _dataTable = dt; _ReportTitle = "Shop to Shop Cash Transfer Details"; _ReportTitleSecondLine = "Transfer # " + _dataTable.Rows[0]["TRANSFERNUMBER"].ToString(); bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate()); try { //set up RunReport event overrides & create doc string reportFileName = Path.GetFullPath(reportObject.ReportTempFileFullName); if (!Directory.Exists(Path.GetDirectoryName(reportFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(reportFileName)); } PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportFileName, FileMode.Create)); writer.PageEvent = this; PdfPTable table = new PdfPTable(_Columns); Image gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); gif.ScalePercent(35); _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL); document.AddTitle(reportObject.ReportTitle); document.SetPageSize(PageSize.HALFLETTER.Rotate()); document.SetMargins(-50, -55, 10, 45); table.HeaderRows = 8; PrintReportHeader(table, gif); PrintReportDetailHeader(table); table.SetWidths(new float[] { 1.5f, 2, 1.5f, 2 }); PrintReportDetailValues(table); PrintReportDetailFooter(table); document.Open(); document.Add(table); document.Close(); isSuccessful = true; } catch (DocumentException de) { reportObject.ReportError = de.Message; reportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { reportObject.ReportError = ioe.Message; reportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public bool CreateReport() { bool isSuccessful = false; var document = new iTextSharp.text.Document(PageSize.LETTER); try { //set up RunReport event overrides & create doc //ReportObject.BuildChargeOffsList(); ReportObject.ReportTempFile = "c:\\Program Files\\Phase2App\\logs\\AuditReportsTemp\\"; ReportObject.CreateTemporaryFullName("InventorySummaryResponseReport"); _pageCount = 1; var events = this; var writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 120, document.PageSize.Height); float pageLeft = document.PageSize.Left; float pageright = document.PageSize.Right; columns.AddSimpleColumn(20, document.PageSize.Width - 20); //set up tables, etc... var cell = new PdfPCell(); var gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new RunReport(); document.Open(); document.SetPageSize(PageSize.LETTER); document.SetMargins(-100, -100, 10, 45); document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy")); var additionalCommentsSectionTable = new PdfPTable(1); additionalCommentsSectionTable.WidthPercentage = 100;// document.PageSize.Width; WriteAdditionalCommentsSection(additionalCommentsSectionTable); columns.AddElement(additionalCommentsSectionTable); var deficiencesSectionTable = new PdfPTable(4); deficiencesSectionTable.WidthPercentage = 100;// document.PageSize.Width; WriteDeficiencesSection(deficiencesSectionTable); columns.AddElement(deficiencesSectionTable); var inventoryHistorySectionTable = new PdfPTable(9); inventoryHistorySectionTable.WidthPercentage = 100;// document.PageSize.Width; WriteInventoryHistorySection(inventoryHistorySectionTable); columns.AddElement(inventoryHistorySectionTable); document.Add(columns); document.Close(); OpenFile(ReportObject.ReportTempFileFullName); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; //ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; //ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public byte[] ToPDF() { try { byte[] pdfBytes; using (MemoryStream ms = new MemoryStream()) { iTextSharp.text.Document doc = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(doc, ms); iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Content/Images/InvoiceSheet/blank_invoice.jpg")); doc.SetPageSize(iTextSharp.text.PageSize.A4); jpg.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); jpg.Alignment = iTextSharp.text.Image.UNDERLYING; jpg.SetAbsolutePosition(10, -5); doc.Open(); doc.Add(jpg); Font defaultFont = new Font(Font.FontFamily.HELVETICA, 7); var cb = writer.DirectContent; ColumnText desc_col = new ColumnText(cb); ColumnText item_col = new ColumnText(cb); ColumnText item_price_col = new ColumnText(cb); ColumnText purchase_col = new ColumnText(cb); ColumnText invoice_col = new ColumnText(cb); ColumnText invoice_date_col = new ColumnText(cb); ColumnText total_sub_price_col = new ColumnText(cb); ColumnText vat_col = new ColumnText(cb); ColumnText total_price_col = new ColumnText(cb); ColumnText job_title_col = new ColumnText(cb); job_title_col.SetSimpleColumn(165, doc.Top - 200, 500, 200, 15, Element.ALIGN_TOP); invoice_col.SetSimpleColumn(doc.Right - 110, doc.Top - 154.2f, 500, 100, 15, Element.ALIGN_TOP); invoice_date_col.SetSimpleColumn(doc.Right - 110, doc.Top - 166.3f, 500, 100, 15, Element.ALIGN_TOP); purchase_col.SetSimpleColumn(200, doc.Top - 270, 500, 100, 15, Element.ALIGN_TOP); desc_col.SetSimpleColumn(165, doc.Top - 320, 415, 200, 15, Element.ALIGN_TOP); item_col.SetSimpleColumn(165, doc.Top - 340, 415, 200, 15, Element.ALIGN_TOP); item_price_col.SetSimpleColumn(doc.Right - 110, doc.Top - 340, 500, 100, 15, Element.ALIGN_TOP); total_sub_price_col.SetSimpleColumn(doc.Right - 110, doc.Bottom - 100, 500, 145, 15, Element.ALIGN_TOP); vat_col.SetSimpleColumn(doc.Right - 110, doc.Bottom - 100, 500, 125, 15, Element.ALIGN_TOP); total_price_col.SetSimpleColumn(doc.Right - 110, doc.Bottom, 500, 105, 15, Element.ALIGN_TOP); job_title_col.AddElement(CreateInfo(this.Title)); invoice_col.AddElement(CreateInfo(this.InvoiceNumber.ToString())); invoice_date_col.AddElement(CreateInfo(this.CreatedDate.ToString("dd MMM yyyy"))); purchase_col.AddElement(CreateInfo(this.PurchaseOrder)); desc_col.AddElement(CreateInfoLight(this.Description)); vat_col.AddElement(CreateInfoLight("20%")); // add invoice items to page var items = this.Items; foreach (var item in items) { item_col.AddElement(CreateInfoLight("item title")); item_price_col.AddElement(CreateInfoLight(item.Value.ToString())); } //totals total_sub_price_col.AddElement(CreateInfo(this.SubValue.ToString("C"))); total_price_col.AddElement(CreateInfo(this.TotalValue.ToString("C"))); job_title_col.Go(); purchase_col.Go(); invoice_col.Go(); invoice_date_col.Go(); desc_col.Go(); item_col.Go(); item_price_col.Go(); total_sub_price_col.Go(); total_price_col.Go(); vat_col.Go(); // column9.Go(); // column10.Go(); // column11.Go(); doc.Close(); pdfBytes = ms.ToArray(); } return(pdfBytes); } catch (Exception) { throw; } }
/// <summary> /// Concatenates two or more PDF files into one file. /// </summary> /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param> /// <param name="outputFile">Name of the concatenated file.</param> public void ConcatenatePDFFiles(String[] inputFiles, String outputFile) { if (inputFiles != null && inputFiles.Length > 0) { if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile)) { var concatDocument = new iTextSharpText.Document(); var outputCopy = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); concatDocument.Open(); try { for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++) { var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]); for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++) { concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop)); outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop)); } inputDocument.Close(); outputCopy.FreeReader(inputDocument); inputDocument = null; } concatDocument.Close(); outputCopy.Close(); } catch { if (concatDocument != null && concatDocument.IsOpen()) concatDocument.Close(); if (outputCopy != null) outputCopy.Close(); if (File.Exists(outputFile)) { try { File.Delete(outputFile); } catch { } } throw; } } else { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } } else { throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString); } }