public void DrawBorder(iTextSharp.text.pdf.PdfContentByte contentByte, iTextSharp.text.Rectangle rectangle, ICSharpCode.Reports.Core.Exporter.IBaseStyleDecorator style) { if (contentByte == null) { throw new ArgumentNullException("contentByte"); } contentByte.SetColorStroke(style.PdfFrameColor); contentByte.SetLineWidth(UnitConverter.FromPixel(baseline.Thickness).Point); contentByte.MoveTo(rectangle.Left, rectangle.Top); contentByte.LineTo(rectangle.Left, rectangle.Top - rectangle.Height); contentByte.LineTo(rectangle.Left + rectangle.Width, rectangle.Top - rectangle.Height); contentByte.LineTo(rectangle.Left + rectangle.Width, rectangle.Top); contentByte.LineTo(rectangle.Left, rectangle.Top); contentByte.FillStroke(); contentByte.ResetRGBColorFill(); }
private void button2_Click(object sender, EventArgs e) { if (textBox1.Text.Trim() != string.Empty) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0); // creation of the different writers iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\temp\Converted.pdf", System.IO.FileMode.Create)); // load the tiff image and count the total pages System.Drawing.Bitmap bm = new System.Drawing.Bitmap(this.openFileDialog1.FileName); int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; for (int k = 0; k < total; ++k) { bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Tiff); img.SetAbsolutePosition(0, 0); img.ScaleAbsoluteHeight(document.PageSize.Height); img.ScaleAbsoluteWidth(document.PageSize.Width); cb.AddImage(img); document.NewPage(); } document.Close(); axAcroPDF1.LoadFile(@"C:\temp\Converted.pdf"); } }
public override void CreatePath(iTextSharp.text.pdf.PdfContentByte contentByte, BaseLine line, IBaseStyleDecorator style, iTextSharp.text.Rectangle rectangle) { if (contentByte == null) { throw new ArgumentNullException("contentByte"); } if (rectangle == null) { throw new ArgumentNullException("rectangle"); } if ((line == null) || (line.Thickness < 1)) { BaseShape.FillBackGround(contentByte, style, rectangle); } else if ((style.BackColor == GlobalValues.DefaultBackColor)) { BaseShape.SetupShape(contentByte, style); contentByte.SetLineWidth(UnitConverter.FromPixel(line.Thickness).Point); contentByte.Ellipse(rectangle.Left, rectangle.Top, rectangle.Left + rectangle.Width, rectangle.Top - rectangle.Height); BaseShape.FinishShape(contentByte); } else { BaseShape.FillBackGround(contentByte, style, rectangle); } }
/// <summary> /// 利用itextsharp生成文字签名 /// </summary> public void ConvertPdf2() { string sourcePath = $"C:\\test\\source.pdf"; string targetPath = $"E:\\test\\target.pdf"; string fontPath = $"C:\\Windows\\Fonts\\simkai.ttf"; //读原始PDF using (iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourcePath)) { //定义流 using (iTextSharp.text.pdf.PdfStamper stream = new iTextSharp.text.pdf.PdfStamper(reader, new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None))) { //加载字体 iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.pdf.BaseFont.CreateFont(fontPath, iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED), 12); //获取顶层图层 iTextSharp.text.pdf.PdfContentByte canvas = stream.GetOverContent(1); iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名1", font), 3090, 93, 0); //left, bottom, rotation iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名2", font), 3090, 73, 0); //left, bottom, rotation iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名3", font), 3090, 53, 0); //left, bottom, rotation iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名4", font), 3090, 33, 0); //left, bottom, rotation } } }
// http://www.mikesdotnetting.com/Article/88/iTextSharp-Drawing-shapes-and-Graphics public override void CreatePath(iTextSharp.text.pdf.PdfContentByte contentByte, BaseLine line, IBaseStyleDecorator style, iTextSharp.text.Rectangle rectangle) { if (contentByte == null) { throw new ArgumentNullException("contentByte"); } if (style == null) { throw new ArgumentNullException("style"); } if (rectangle == null) { throw new ArgumentNullException("rectangle"); } if (line == null) { BaseShape.FillBackGround(contentByte, style, rectangle); } else { BaseShape.SetupShape(contentByte, style); contentByte.SetLineWidth(UnitConverter.FromPixel(line.Thickness).Point); contentByte.RoundRectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height, CornerRadius); BaseShape.FinishShape(contentByte); } }
public override void CreatePath(iTextSharp.text.pdf.PdfContentByte contentByte, BaseLine line, IBaseStyleDecorator style, iTextSharp.text.Rectangle rectangle) { throw new NotImplementedException(); }
static private string WriteCompatiblePdf(string sFilename) { // string s = System.IO.Path.GetTempPath(); string sNewPdf = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf"; sNewPdfs.Add(sNewPdf); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sFilename); // we retrieve the total number of pages int n = reader.NumberOfPages; // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(sNewPdf, FileMode.Create)); //write pdf that pdfsharp can understand writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4); // 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; 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); } } // step 5: we close the document document.Close(); return(sNewPdf); }
public static bool PerfectBind_LayoutCroppedBrief(string src) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "pb on B5.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.Document docB5 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(515.76f, 728.4f)); // B5 sized page iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB5, stream); docB5.Open(); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); for (int i = 1; i <= reader.NumberOfPages; i++) { if (i != 1) { docB5.NewPage(); } docB5.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate t = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015 if (i % 2 == 1) { contentbyte.AddTemplate(t, /*42.5f*/ 35.5f, -141.75f); // position for front side of B5 sheet } else if (i % 2 == 0) { contentbyte.AddTemplate(t, /*110f*/ 110f, -141.75f); // position for back side of B5 sheet } else { throw new Exception(); } } docB5.Close(); reader.Close(); } System.IO.File.Delete(src); System.IO.File.Move(dest, src); return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
public override void CreatePath(iTextSharp.text.pdf.PdfContentByte contentByte, BaseLine line, IBaseStyleDecorator style, Point from, Point to) { if (contentByte == null) { throw new ArgumentNullException("contentByte"); } BaseShape.SetupShape(contentByte, style); contentByte.SetLineWidth(UnitConverter.FromPixel(line.Thickness).Point); contentByte.MoveTo(from.X, from.Y); contentByte.LineTo(to.X, to.Y); BaseShape.FinishShape(contentByte); }
/// <summary> /// from http://forum.pdfsharp.net/viewtopic.php?p=2069 /// uses itextsharp to convert any pdf to 1.4 compatible pdf /// </summary> static private string WritePdf1pt4Version(string inputPath) { var tempFileName = Path.GetTempFileName(); File.Delete(tempFileName); string outputPath = tempFileName + ".pdf"; iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(inputPath); // we retrieve the total number of pages int n = reader.NumberOfPages; // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); //write pdf that pdfsharp can understand writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4); // 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; 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); } } // step 5: we close the document document.Close(); return(outputPath); }
private System.IO.MemoryStream imposeTypesetPerfectBindBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var docB5 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(515.76f, 728.4f)); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB5, dest_stream); docB5.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (int i = 1; i <= reader.NumberOfPages; i++) { if (i != 1) { docB5.NewPage(); } docB5.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate t = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015 if (i % 2 == 1) { contentbyte.AddTemplate(t, /*42.5f*/ 35.5f, -141.75f); // position for front side of B5 sheet } else if (i % 2 == 0) { contentbyte.AddTemplate(t, /*110f*/ 110f, -141.75f); // position for back side of B5 sheet } } docB5.Close(); reader.Close(); writer.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
public static bool SaddleStitch_LayoutCroppedBrief(string src) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "ss on B4.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.Document docB4 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(1031.76f, 728.64f)); // B4 sized page iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB4, stream); docB4.Open(); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); for (int i = 1; i <= reader.NumberOfPages; i += 2) { if (i != 1) { docB4.NewPage(); } docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tLeft = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfTemplate tRight = writer.GetImportedPage(reader, i + 1); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015; RETESTED TO MATCH 951s, 11/17/2015 // RETESTED AGAIN FOR 951A, where most saddle stitches will print contentbyte.AddTemplate(tLeft, /*113f*/ 108f /*110f*/, -126f); // position for left side of B4 sheet contentbyte.AddTemplate(tRight, /*554.5f*/ /*550.5f*/ 554.5f, -126f); // position for right side of B4 sheet } docB4.Close(); reader.Close(); } System.IO.File.Delete(src); System.IO.File.Move(dest, src); return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
private System.IO.MemoryStream imposeTypesetSaddleStitchBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var docB4 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(1031.76f, 728.64f)); // B4 sized page var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB4, dest_stream); docB4.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (int i = 1; i <= reader.NumberOfPages; i += 2) { if (i != 1) { docB4.NewPage(); } docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tLeft = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfTemplate tRight = writer.GetImportedPage(reader, i + 1); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015; RETESTED TO MATCH 951s, 11/17/2015 // RETESTED AGAIN FOR 951A, where most saddle stitches will print contentbyte.AddTemplate(tLeft, /*113f*/ 108f /*110f*/, -126f); // position for left side of B4 sheet contentbyte.AddTemplate(tRight, /*554.5f*/ /*550.5f*/ 554.5f, -126f); // position for right side of B4 sheet } docB4.Close(); reader.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
public static byte[] CreatePdfDataFromAssignment(SqlConnection conn, SqlTransaction trans, Guid assignmentId) { string OrderName = "", LaboratoryName = "", ResponsibleName = "", CustomerName = "", CustomerCompany = "", CustomerAddress = ""; PdfImage labLogo = null; using (SqlDataReader reader = DB.GetDataReader(conn, trans, "csp_select_assignment_flat", CommandType.StoredProcedure, new SqlParameter("@id", assignmentId))) { if (reader.HasRows) { reader.Read(); OrderName = reader.GetString("name"); LaboratoryName = reader.GetString("laboratory_name"); ResponsibleName = reader.GetString("account_name"); CustomerName = reader.GetString("customer_contact_name"); CustomerCompany = reader.GetString("customer_company_name"); CustomerAddress = reader.GetString("customer_contact_address"); } } Guid labId = (Guid)DB.GetScalar(conn, trans, "select laboratory_id from assignment where id = @id", CommandType.Text, new SqlParameter("@id", assignmentId)); if (Utils.IsValidGuid(labId)) { using (SqlDataReader reader = DB.GetDataReader(conn, trans, "select laboratory_logo from laboratory where id = @id", CommandType.Text, new SqlParameter("@id", labId))) { if (reader.HasRows) { reader.Read(); if (DB.IsValidField(reader["laboratory_logo"])) { labLogo = PdfImage.GetInstance((byte[])reader["laboratory_logo"]); } } } } byte[] pdfData = null; PdfDocument document = null; MemoryStream ms = null; try { ms = new MemoryStream(); document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); PdfBaseFont baseFont = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_ROMAN, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED); PdfBaseFont baseFontBold = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_BOLD, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED); PdfBaseFont baseFontItalic = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_ITALIC, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED); float fontSize = 10, fontSizeHeader = 14; float margin = 50; float leftCursor = margin, topCursor = document.Top - margin, lineSpace = 13; bool hasLogos = false; if (labLogo != null) { CropImageToHeight(labLogo, 64f); labLogo.SetAbsolutePosition(leftCursor, topCursor); document.Add(labLogo); hasLogos = true; } if (hasLogos) { topCursor -= labLogo.ScaledHeight; } cb.SetFontAndSize(baseFontBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "OPPDRAGSOVERSIKT", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFont, fontSize); topCursor -= lineSpace * 2; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdrag: " + OrderName, leftCursor, topCursor, 0); topCursor -= lineSpace; string cust = CustomerName; if (!String.IsNullOrEmpty(CustomerCompany)) { cust += ", " + CustomerCompany; } cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver: " + cust, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, CustomerAddress, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Laboratorium/Kontaktperson: " + LaboratoryName + " / " + ResponsibleName, leftCursor, topCursor, 0); topCursor -= lineSpace * 4; cb.SetFontAndSize(baseFontBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Måleresultater", leftCursor, topCursor, 0); cb.EndText(); topCursor -= lineSpace; PdfPTable table = new PdfPTable(13); table.TotalWidth = document.GetRight(margin) - document.GetLeft(margin); PdfPCell cell = new PdfPCell(GetHeaderPhrase("Analysis")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Sample Type")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("P.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("A.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Method")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Nuclide")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Activity")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Unc.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Reportable")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Accredited")); table.AddCell(cell); string query = @" select s.number as 'sample', st.name as 'sample_type_name', sc.name as 'sample_component_name', p.number as 'preparation', pm.name_short as 'preparation_method', p.workflow_status_id as 'preparation_wfstatus', a.number as 'analysis', a.workflow_status_id as 'analysis_wfstatus', am.name_short as 'analysis_method', n.name as 'nuclide_name', ar.activity as 'act', ar.activity_uncertainty_abs as 'act.unc', ar.activity_approved as 'act.appr', ar.detection_limit as 'det.lim', ar.detection_limit_approved as 'det.lim.appr', ar.reportable, ar.accredited from sample s inner join sample_type st on st.id = s.sample_type_id left outer join sample_component sc on sc.id = s.sample_component_id inner join preparation p on p.sample_id = s.id and p.instance_status_id <= 1 inner join preparation_method pm on pm.id = p.preparation_method_id inner join analysis a on a.preparation_id = p.id and a.instance_status_id <= 1 and a.assignment_id = @assignment_id inner join analysis_result ar on ar.analysis_id = a.id inner join analysis_method am on am.id = a.analysis_method_id inner join nuclide n on n.id = ar.nuclide_id order by s.number, p.number, a.number "; int nRows = 1; using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] { new SqlParameter("@assignment_id", assignmentId) })) { while (reader.Read()) { int pwfstat = reader.GetInt32("preparation_wfstatus"); string spwfstat = "Unknown"; switch (pwfstat) { case WorkflowStatus.Construction: spwfstat = "Construction"; break; case WorkflowStatus.Complete: spwfstat = "Complete"; break; case WorkflowStatus.Rejected: spwfstat = "Rejected"; break; } int awfstat = reader.GetInt32("analysis_wfstatus"); string sawfstat = "Unknown"; switch (awfstat) { case WorkflowStatus.Construction: sawfstat = "Construction"; break; case WorkflowStatus.Complete: sawfstat = "Complete"; break; case WorkflowStatus.Rejected: sawfstat = "Rejected"; break; } string sact = ""; if (DB.IsValidField(reader["act"])) { sact = reader.GetDouble("act").ToString(Utils.ScientificFormat); } string sactunc = ""; if (DB.IsValidField(reader["act.unc"])) { sactunc = reader.GetDouble("act.unc").ToString(Utils.ScientificFormat); } string sdetlim = ""; if (DB.IsValidField(reader["det.lim"])) { sdetlim = reader.GetDouble("det.lim").ToString(Utils.ScientificFormat); } cell = new PdfPCell(GetCellPhrase(reader.GetString("sample") + "/" + reader.GetString("preparation") + "/" + reader.GetString("analysis"))); table.AddCell(cell); string sampleType = reader.GetString("sample_type_name"); if (DB.IsValidField(reader["sample_component_name"])) { sampleType += " / " + reader.GetString("sample_component_name"); } cell = new PdfPCell(GetCellPhrase(sampleType)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(spwfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sawfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("preparation_method") + " / " + reader.GetString("analysis_method"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("nuclide_name"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sact)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sactunc)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("act.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sdetlim)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("det.lim.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("reportable"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("accredited"))); table.AddCell(cell); nRows++; } } float currHeight = topCursor; int currRow = 0, pageRows = 0; for (int i = 0; i < nRows; i++) { currHeight -= table.GetRowHeight(i); pageRows++; if (currHeight <= document.GetBottom(10f)) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); currRow += pageRows; currHeight = topCursor = document.GetTop(10f); pageRows = 0; } } if (pageRows > 0) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); } } finally { document?.Close(); if (ms != null) { pdfData = ms.GetBuffer(); } } return(pdfData); }
public void MergePdf(string[] pdfFiles, string outputPath) { int pdfCount = 0; int f = 0; string filename = String.Empty; iTextSharp.text.pdf.PdfReader reader = null; int pageCount = 0; iTextSharp.text.Document pdfDoc = null; iTextSharp.text.pdf.PdfWriter writer = null; iTextSharp.text.pdf.PdfContentByte cb = null; iTextSharp.text.pdf.PdfImportedPage page = null; int rotation = 0; iTextSharp.text.Font bookmarkFont = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 4, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.RED); try { pdfCount = pdfFiles.Length; if (pdfCount > 1) { filename = pdfFiles[f]; reader = new iTextSharp.text.pdf.PdfReader(filename); pageCount = reader.NumberOfPages; pdfDoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18); writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new System.IO.FileStream(outputPath, System.IO.FileMode.Create)); pdfDoc.AddAuthor("OPGK w Lublinie sp. z o. o. Sławomir Aleksak"); pdfDoc.AddCreator("Konwerter"); pdfDoc.Open(); cb = writer.DirectContent; while (f < pdfCount) { var i = 0; while (i < pageCount) { i += 1; pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i)); pdfDoc.NewPage(); if (i == 1) { iTextSharp.text.Paragraph para = new iTextSharp.text.Paragraph(System.IO.Path.GetFileName(filename).ToUpper(), bookmarkFont); iTextSharp.text.Chapter chpter = new iTextSharp.text.Chapter(para, f + 1); pdfDoc.Add(chpter); } page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90) { cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height); } if (rotation == 270) { cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30); } else { cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0); } } f += 1; if (f < pdfCount) { filename = pdfFiles[f]; reader = new iTextSharp.text.pdf.PdfReader(filename); pageCount = reader.NumberOfPages; } } pdfDoc.Close(); } } catch (Exception ex) { throw ex; } }
void CreateFromRawdataFile(string sourceTxtPath, string destinationPDFPath) { pdfdoc = new iTextSharp.text.Document(); pdfdoc.SetPageSize(currentPageSize); gridCountInBlockRowHorizontal = (int)(currentPageSize.Width / gridSideLength); blockRowHeight = gridSideLength * gridCountInBlockRowVertical; blockRowCount = (int)(currentPageSize.Height / (blockRowHeight + blockRowInterval)); rawDataCountInBlockRow = (int)(gridCountInBlockRowHorizontal * 40 * 512 / 1000); rawDataInterval = currentPageSize.Width / rawDataCountInBlockRow; Debug.Log("gridCountInBlockRowHorizontal:" + gridCountInBlockRowHorizontal); Debug.Log("rawDataCountInBlockRow" + rawDataCountInBlockRow); if (File.Exists(destinationPDFPath)) { File.Delete(destinationPDFPath); } pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(destinationPDFPath, FileMode.CreateNew)); pdfdoc.Open(); iTextSharp.text.pdf.PdfContentByte cb = pdfwriter.DirectContent; pdfdoc.NewPage(); blockRowIndex = 0; rawDataIndex = 0; iTextSharp.text.pdf.BaseFont font = iTextSharp.text.pdf.BaseFont.CreateFont(); cb.SetFontAndSize(font, 60); cb.BeginText(); cb.SetTextMatrix(100, currentPageSize.Height - 50); cb.ShowText("Test String ......."); cb.EndText(); System.IO.StreamReader reader = new StreamReader(sourceTxtPath); string theLine; int rawData; while (!reader.EndOfStream) { theLine = reader.ReadLine(); try{ rawData = int.Parse(theLine); }catch (Exception e) { Debug.Log("Exception"); continue; } rawData = rawData > maxRawData ? maxRawData : rawData; rawData = rawData < -maxRawData ? -maxRawData : rawData; scaledRawData = (rawData * (blockRowHeight / 2)) / maxRawData; if (rawDataIndex == 0) { currentBaseLine = currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + (blockRowHeight / 2)); cb.SetColorStroke(iTextSharp.text.BaseColor.RED); //draw horizontal lines for (int i = 0; i <= gridCountInBlockRowVertical; i++) { if (i % 5 == 0) { cb.SetLineWidth(2.5f); } else { cb.SetLineWidth(0.5f); } cb.MoveTo(0, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + i * gridSideLength)); cb.LineTo(currentPageSize.Width, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + i * gridSideLength)); cb.Stroke(); } //draw vertical lines for (int j = 0; j <= gridCountInBlockRowHorizontal; j++) { if (j % 5 == 0) { cb.SetLineWidth(2.5f); } else { cb.SetLineWidth(0.5f); } cb.MoveTo(j * gridSideLength, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval))); cb.LineTo(j * gridSideLength, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + blockRowHeight)); cb.Stroke(); } //prepare to draw ECG cb.SetLineWidth(1.5f); cb.SetColorStroke(iTextSharp.text.BaseColor.BLACK); cb.MoveTo(0, currentBaseLine); } cb.LineTo(rawDataIndex * rawDataInterval, currentBaseLine + scaledRawData); rawDataIndex++; if (rawDataIndex >= rawDataCountInBlockRow) { cb.Stroke(); rawDataIndex = 0; blockRowIndex++; } } cb.Stroke(); reader.Close(); pdfdoc.Dispose(); System.Diagnostics.Process.Start(destinationPDFPath); }
/// <summary>Converts the Tif files into a multi page PDF multiple.</summary> /// <param name="sourceDir">The source dir.</param> /// <param name="destinationDir">The destination dir.</param> /// <exception cref="System.Exception">Source folder '"+ sourceDir + "' contains no files!!!</exception> private static void ConvertMultiple(string sourceDir, string destinationDir) { try { DirectoryInfo di = new DirectoryInfo(sourceDir); int totalFiles = di.GetFiles().Length; if (totalFiles == 0) { throw new System.Exception("Source folder '" + sourceDir + "' contains no files!!!"); } Console.WriteLine("Total Files in Source Folder = " + totalFiles); foreach (var file in di.GetFiles()) { totalFiles = totalFiles -= 1; if (file.Extension.ToString() == ".tif" || file.Extension.ToString() == ".tiff") { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0); string fileName = Path.GetFileNameWithoutExtension(file.ToString()); string filePath = string.Format("{0}\\{1}.{2}", destinationDir, fileName, "pdf"); string sourceFilePath = string.Format("{0}\\{1}.{2}", sourceDir, fileName, "tif"); FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs); // Counts the files remaining to be converting Console.WriteLine("Converting: " + file.Name + " Total Files Left: " + totalFiles); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(sourceFilePath); document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; int total = bmp.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); for (int k = 0; k < total; ++k) { bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Bmp); // Scale the image to fit in the page img.ScalePercent(72f / img.DpiX * 100); img.SetAbsolutePosition(0, 0); cb.AddImage(img); document.NewPage(); } bmp.Dispose(); writer.Flush(); document.Close(); document.Dispose(); } else { Console.WriteLine("Not Converting: " + file.Name + " Total Files Left: " + totalFiles); } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ForegroundColor = ConsoleColor.Gray; } }
public Boolean Obtener_Pdf_CC(String pRutaArchivo, FirmaElectronicaModel oFirmaElectronicaModel, String pImg64) //Fin E.Z. 13/05/2016 { Boolean b_Resultado = false; iTextSharp.text.Document oDocument = null; iTextSharp.text.pdf.PdfWriter oPdfWriter = null; iTextSharp.text.pdf.PdfContentByte oPdfContentByte = null; iTextSharp.text.Chunk oChunk = null; iTextSharp.text.HeaderFooter oFooter = null; try { using (FileStream fs = new FileStream(pRutaArchivo, FileMode.Create, FileAccess.Write)) { // Crear PDF oDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30, 30, 15, 25); oPdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(oDocument, fs); oDocument.Open(); oPdfContentByte = oPdfWriter.DirectContent; oPdfContentByte.Stroke(); oPdfContentByte.SetLineWidth(0.2f); oDocument.Add(Obtener_Logos(null)); oDocument.Add(Obtener_Blanco()); oDocument.Add(Obtener_Titulo("098923")); oDocument.Add(Obtener_Blanco()); oDocument.Add(Obtener_Cliente(oFirmaElectronicaModel)); oDocument.Add(Obtener_Blanco()); oDocument.Add(Obtener_Cuenta(oFirmaElectronicaModel)); oDocument.Add(Obtener_Blanco()); oDocument.Add(Obtener_Solicitud(oFirmaElectronicaModel, "ARamirez")); oDocument.Add(Obtener_Blanco()); oDocument.Add(Obtener_Blanco()); oDocument.Add(Obtener_Pie(oFirmaElectronicaModel)); #region "Firma" //Firma 1 //oPdfContentByte.Rectangle(59f, 40.5f, 300f, 72.5f); oPdfContentByte.BeginText(); oPdfContentByte.SetFontAndSize(iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, iTextSharp.text.pdf.BaseFont.WINANSI, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED), (float)8); oPdfContentByte.ShowTextAligned(iTextSharp.text.Element.ALIGN_BASELINE, "Asesor de Servicio al Cliente Finantienda", 59f, 122.5f, 0); oPdfContentByte.EndText(); oPdfContentByte.Stroke(); oPdfContentByte.BeginText(); oPdfContentByte.SetFontAndSize(iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.WINANSI, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED), (float)8); oPdfContentByte.ShowTextAligned(iTextSharp.text.Element.ALIGN_BASELINE, "Cesar Mariñoas Asmat", 59f, 102.5f, 0); oPdfContentByte.EndText(); oPdfContentByte.Stroke(); oPdfContentByte.Rectangle(385.5f, 40.5f, 150f, 72.5f); oPdfContentByte.BeginText(); oPdfContentByte.SetFontAndSize(iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, iTextSharp.text.pdf.BaseFont.WINANSI, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED), (float)8); oPdfContentByte.ShowTextAligned(iTextSharp.text.Element.ALIGN_BASELINE, "Firma del Cliente Titular", 430.5f, 122.5f, 0); oPdfContentByte.EndText(); oPdfContentByte.Stroke(); if (!string.IsNullOrEmpty(pImg64)) { iTextSharp.text.Image _imagen = iTextSharp.text.Image.GetInstance(ConvertStringBase64ToImage(oFirmaElectronicaModel.oFirmaElectronica.SIGSTRING_64)); _imagen.Border = iTextSharp.text.Rectangle.NO_BORDER; _imagen.BorderColor = iTextSharp.text.Color.WHITE; _imagen.SetAbsolutePosition(385.5f, 55.8f); _imagen.ScaleToFit(150f, 81.5f); oDocument.Add(_imagen); } oDocument.Close(); b_Resultado = true; } #endregion } catch (Exception ex) { b_Resultado = false; } // return(b_Resultado); }
public void Draw(iTextSharp.text.pdf.PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { // }
private static void MergeFiles(string destinationFile, string[] sourceFiles) { if (System.IO.File.Exists(destinationFile)) { System.IO.File.Delete(destinationFile); } string[] sSrcFile; sSrcFile = new string[sourceFiles.Count()]; string[] arr = new string[sourceFiles.Count()]; for (int i = 0; i <= sourceFiles.Length - 1; i++) { if (sourceFiles[i] != null) { if (sourceFiles[i].Trim() != "") { arr[i] = sourceFiles[i].ToString(); } } } if (arr != null) { sSrcFile = new string[sourceFiles.Count()]; for (int ic = 0; ic <= arr.Length - 1; ic++) { sSrcFile[ic] = arr[ic].ToString(); } } try { int f = 0; iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sSrcFile[f]); int n = reader.NumberOfPages; using (iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4)) { iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create)); document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; iTextSharp.text.pdf.PdfImportedPage page; int rotation; while (f < sSrcFile.Length) { int i = 0; while (i < n) { i++; document.SetPageSize(iTextSharp.text.PageSize.A4); 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); } //Response.Write("\n Processed page " + i); } f++; if (f < sSrcFile.Length) { reader = new iTextSharp.text.pdf.PdfReader(sSrcFile[f]); n = reader.NumberOfPages; // Response.Write("There are " + n + " pages in the original file."); } } // Response.Write("Success"); document.Close(); } } catch (Exception e) { // Response.Write(e.Message); } }
private void MultiplePages(string aSourceFile, string aDestFile, int aPages, bool aLandscape) { iTextSharp.text.Document document = null; try { if (aPages < kMultiplePagesMin || aPages > kMultiplePagesMax) { throw new Exception("Multiple Pages only supports " + kMultiplePagesMin + " to " + kMultiplePagesMin + " pages per sheet (Invalid value: " + aPages.ToString() + ")"); } iProgressChanged(0, "Generating Multiple Pages Per Sheet: Initialising Document", Progress.State.eInProgress); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(aSourceFile); int n = reader.NumberOfPages; // step 1: creation of a document-object if (aLandscape && aPages != 2 && aPages != 8 && aPages != 32) // pages = 2,8,32: print landscape pages onto portrait document in landscape orientation { document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate()); // landscape } else { document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); // portrait } // step 2: we create a writer that listens to the document iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(aDestFile, FileMode.Create)); writer.ViewerPreferences = iTextSharp.text.pdf.PdfWriter.PageLayoutSinglePage; // step 3: we open the document document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; iTextSharp.text.pdf.PdfImportedPage page = null; float[] xPoints = new float[7] { -1f, -1f, -1f, -1f, -1f, -1f, -1f }; float[] yPoints = new float[9] { -1f, -1f, -1f, -1f, -1f, -1f, -1f, -1f, -1f }; int[] xFactors = new int[37] { 0, 1, 1, 0, 2, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 6 }; int[] yFactors = new int[37] { 0, 1, 2, 0, 2, 0, 0, 0, 4, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 6 }; int xFactor = xFactors[aPages]; int yFactor = yFactors[aPages]; float xScaler = 1f / xFactor; float yScaler = 1f / yFactor; float docWidth = document.PageSize.Width; float docHeight = document.PageSize.Height; float specialScaler = (docWidth / docHeight) / xFactor; int pyBase = yFactor; if (!aLandscape) { pyBase--; } for (uint i = 0; i <= xFactor; i++) { xPoints[i] = (docWidth / xFactor) * i; } for (uint i = 0; i <= yFactor; i++) { yPoints[i] = (docHeight / yFactor) * i; } int px = 0; int py = pyBase; int pxSpecial = xFactor - 1; int pySpecial = yFactor; int j = 0; int p = 0; // step 4: we add content int finalTotal = n / aPages; if (n % aPages != 0) { finalTotal++; } int forward = 1; int backwardBase = (finalTotal * aPages) - (aPages / 2) + 1; int backward = backwardBase; int getPage = 0; bool flip = !aLandscape; int forward2 = 0; int backward2 = 0; bool booklet = iPrintOrderBooklet.Enabled && iPrintOrderBooklet.Checked; bool upsideDown = ((aPages == 4 || aPages == 16 || aPages == 36) && !aLandscape && booklet); bool upsideDownSpecial = ((aPages == 2 || aPages == 8 || aPages == 32) && aLandscape && booklet); if (upsideDownSpecial) { upsideDown = true; flip = true; } while (j < n) { j++; iProgressChanged((((j / aPages) + 1) * 100 / finalTotal), "Generating Multiple Pages Per Sheet: Page " + ((j / aPages) + 1) + " of " + finalTotal, Progress.State.eInProgress); if (booklet) { bool test = false; if ((aPages == 2 || aPages == 8 || aPages == 32) && !aLandscape) { test = (pySpecial <= (yFactor / 2)); } else { if (upsideDownSpecial) { test = (py <= (yFactor / 2)); } else if (upsideDown) { test = (py < (yFactor / 2)); } else { test = (px < (xFactor / 2)); } } if (test) { if (!flip) { getPage = backward++; backwardBase--; if (upsideDown) { getPage = forward2--; } } else { getPage = forward++; } } else { if (!flip) { getPage = forward++; if (upsideDown) { getPage = backward2--; } } else { getPage = backward++; backwardBase--; } } } else { getPage = j; } if (getPage <= n) { page = writer.GetImportedPage(reader, getPage); } else { j--; } if (p == 0) { // draw layout lines (once per destination document page) cb.SetRGBColorStroke(0xC0, 0xC0, 0xC0); foreach (float xPoint in xPoints) { if (xPoint >= 0) { cb.MoveTo(xPoint, 0); cb.LineTo(xPoint, docHeight); if (docWidth > docHeight && booklet) { if (xPoint == (docWidth / 2)) { cb.SetLineDash(2f, 4f, 0); } } cb.Stroke(); cb.SetLineDash(0); } } foreach (float yPoint in yPoints) { if (yPoint >= 0) { cb.MoveTo(0, yPoint); cb.LineTo(docWidth, yPoint); if (docHeight > docWidth && booklet) { if (yPoint == (docHeight / 2)) { cb.SetLineDash(2f, 4f, 0); } } cb.Stroke(); cb.SetLineDash(0); } } } if (getPage <= n) { if (aPages == 2 || aPages == 8 || aPages == 32) { if (aLandscape) { if (upsideDown && !flip) { cb.AddTemplate(page, 0, specialScaler, -specialScaler, 0, xPoints[px + 1], yPoints[py - 1]); } else { cb.AddTemplate(page, 0, -specialScaler, specialScaler, 0, xPoints[px], yPoints[py]); } } else { cb.AddTemplate(page, 0, -specialScaler, specialScaler, 0, xPoints[pxSpecial], yPoints[pySpecial]); } } else { if (aLandscape) { cb.AddTemplate(page, 0, -xScaler, yScaler, 0, xPoints[px], yPoints[py]); } else { if (upsideDown && !flip) { cb.AddTemplate(page, -xScaler, 0, 0, -yScaler, xPoints[px + 1], yPoints[py + 1]); } else { cb.AddTemplate(page, xScaler, 0, 0, yScaler, xPoints[px], yPoints[py]); } } } } cb.Stroke(); p++; if ((p % xFactor) == 0) { px = 0; py--; } else { px++; } if ((p % yFactor) == 0) { pxSpecial--; pySpecial = yFactor; } else { pySpecial--; } if (p == aPages) { p = 0; px = 0; py = pyBase; pxSpecial = xFactor - 1; pySpecial = yFactor; backward = backwardBase; forward2 = (forward - 1) + (aPages / 2); backward2 = (backward - 1) + (aPages / 2); flip = !flip; document.NewPage(); } } iProgressChanged(100, "Generating Multiple Pages Per Sheet: Finalising Document", Progress.State.eInProgress); } catch (Exception e) { throw e; } finally { try { // step 5: we close the document if (document != null) { document.Close(); } } catch (System.IO.IOException) { // document has no pages } } }
public static byte[] CreatePdfDataFromDataGridView(DataGridView grid, int startColumn, int endColumn, string title) { byte[] pdfData = null; PdfDocument document = null; MemoryStream ms = null; try { ms = new MemoryStream(); document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); float fontSizeHeader = 14f; float topCursor = document.GetTop(10f); cb.SetFontAndSize(baseFontTimesBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, title, document.GetLeft(10f), topCursor, 0); topCursor -= 20f; cb.EndText(); int nCols = endColumn - startColumn; PdfPTable table = new PdfPTable(nCols); table.TotalWidth = document.GetRight(10) - document.GetLeft(10); for (int i = startColumn; i < endColumn; i++) { PdfPCell cell = new PdfPCell(GetHeaderPhrase(grid.Columns[i].HeaderText)); cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(cell); } for (int i = 0; i < grid.Rows.Count; i++) { for (int j = startColumn; j < endColumn; j++) { PdfPCell cell = new PdfPCell(GetCellPhrase(grid.Rows[i].Cells[j].FormattedValue.ToString())); cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(cell); } } float currHeight = topCursor; int currRow = 0, pageRows = 0, nRows = grid.Rows.Count + 1; for (int i = 0; i < nRows; i++) { currHeight -= table.GetRowHeight(i); pageRows++; if (currHeight <= document.GetBottom(10f)) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); currRow += pageRows; currHeight = topCursor = document.GetTop(10f); pageRows = 0; } } if (pageRows > 0) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); } } finally { document?.Close(); if (ms != null) { pdfData = ms.GetBuffer(); } } return(pdfData); }
public static byte[] CreatePdfDataFromAssignment(SqlConnection conn, SqlTransaction trans, Assignment assignment) { byte[] pdfData = null; PdfDocument document = null; MemoryStream ms = null; try { ms = new MemoryStream(); document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); float fontSize = 10, fontSizeHeader = 16; float margin = 50; float leftCursor = margin, topCursor = document.Top - 10f, lineSpace = 13; PdfImage labLogo = GetLaboratoryLogo(conn, trans, assignment.LaboratoryId); if (labLogo != null) { CropImageToHeight(labLogo, 64f); labLogo.SetAbsolutePosition(document.GetRight(10f) - labLogo.PlainWidth, document.GetTop(10f) - 40f); document.Add(labLogo); } cb.SetFontAndSize(baseFontTimesBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "OPPDRAGSOVERSIKT", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace * 2; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsnummer: " + assignment.Name, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdrag opprettet: " + assignment.CreateDate.ToString(Utils.DateFormatNorwegian), leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Utskriftsdato: " + DateTime.Now.ToString(Utils.DateFormatNorwegian), leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver, Firma/Avd.", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Navn: " + assignment.CustomerCompanyName, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Addresse: " + assignment.CustomerCompanyAddress, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Epost: " + assignment.CustomerCompanyEmail, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telefon: " + assignment.CustomerCompanyPhone, leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver, Kontakt", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Navn: " + assignment.CustomerContactName, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Addresse: " + assignment.CustomerContactAddress, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Epost: " + assignment.CustomerContactEmail, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telefon: " + assignment.CustomerContactPhone, leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Laboratorium", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Navn: " + assignment.LaboratoryName(conn, trans), leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Kontakt: " + assignment.ResponsibleName(conn, trans), leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Måleresultater", leftCursor, topCursor, 0); cb.EndText(); topCursor -= lineSpace; PdfPTable table = new PdfPTable(13); table.TotalWidth = document.GetRight(margin) - document.GetLeft(margin); PdfPCell cell = new PdfPCell(GetHeaderPhrase("Analysis")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Sample Type")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("P.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("A.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Method")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Nuclide")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Activity")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Unc.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Reportable")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Accredited")); table.AddCell(cell); string query = @" select s.number as 'sample', st.name as 'sample_type_name', sc.name as 'sample_component_name', p.number as 'preparation', pm.name_short as 'preparation_method', p.workflow_status_id as 'preparation_wfstatus', a.number as 'analysis', a.workflow_status_id as 'analysis_wfstatus', am.name_short as 'analysis_method', n.name as 'nuclide_name', ar.activity as 'act', ar.activity_uncertainty_abs as 'act.unc', ar.activity_approved as 'act.appr', ar.detection_limit as 'det.lim', ar.detection_limit_approved as 'det.lim.appr', ar.reportable, ar.accredited from sample s inner join sample_type st on st.id = s.sample_type_id left outer join sample_component sc on sc.id = s.sample_component_id inner join preparation p on p.sample_id = s.id and p.instance_status_id = 1 inner join preparation_method pm on pm.id = p.preparation_method_id inner join analysis a on a.preparation_id = p.id and a.instance_status_id = 1 and a.assignment_id = @assignment_id inner join analysis_result ar on ar.analysis_id = a.id and ar.instance_status_id = 1 and ar.reportable = 1 inner join analysis_method am on am.id = a.analysis_method_id inner join nuclide n on n.id = ar.nuclide_id order by s.number, p.number, a.number "; int nRows = 1; using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] { new SqlParameter("@assignment_id", assignment.Id) })) { while (reader.Read()) { int pwfstat = reader.GetInt32("preparation_wfstatus"); string spwfstat = "Unknown"; switch (pwfstat) { case WorkflowStatus.Construction: spwfstat = "Construction"; break; case WorkflowStatus.Complete: spwfstat = "Complete"; break; case WorkflowStatus.Rejected: spwfstat = "Rejected"; break; } int awfstat = reader.GetInt32("analysis_wfstatus"); string sawfstat = "Unknown"; switch (awfstat) { case WorkflowStatus.Construction: sawfstat = "Construction"; break; case WorkflowStatus.Complete: sawfstat = "Complete"; break; case WorkflowStatus.Rejected: sawfstat = "Rejected"; break; } string sact = ""; if (DB.IsValidField(reader["act"])) { sact = reader.GetDouble("act").ToString(Utils.ScientificFormat); } string sactunc = ""; if (DB.IsValidField(reader["act.unc"])) { sactunc = reader.GetDouble("act.unc").ToString(Utils.ScientificFormat); } string sdetlim = ""; if (DB.IsValidField(reader["det.lim"])) { sdetlim = reader.GetDouble("det.lim").ToString(Utils.ScientificFormat); } cell = new PdfPCell(GetCellPhrase(reader.GetString("sample") + " / " + reader.GetString("preparation") + " / " + reader.GetString("analysis"))); table.AddCell(cell); string sampleType = reader.GetString("sample_type_name"); if (DB.IsValidField(reader["sample_component_name"])) { sampleType += " / " + reader.GetString("sample_component_name"); } cell = new PdfPCell(GetCellPhrase(sampleType)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(spwfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sawfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("preparation_method") + " / " + reader.GetString("analysis_method"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("nuclide_name"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sact)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sactunc)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("act.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sdetlim)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("det.lim.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("reportable"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("accredited"))); table.AddCell(cell); nRows++; } } float currHeight = topCursor; int currRow = 0, pageRows = 0; for (int i = 0; i < nRows; i++) { currHeight -= table.GetRowHeight(i); pageRows++; if (currHeight <= document.GetBottom(10f)) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); currRow += pageRows; currHeight = topCursor = document.GetTop(10f); pageRows = 0; } } if (pageRows > 0) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); } } finally { document?.Close(); if (ms != null) { pdfData = ms.GetBuffer(); } } return(pdfData); }
private void CommonConstructor( iTextSharp.text.Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom, System.IO.Stream stream, string fontpath, BackgroundImageDefinition bImageDefinition ){ if(this.fontpath != null)this.fontpath = fontpath; this.margin_left = marginLeft; this.margin_right = marginRight; this.margin_top = marginTop; this.margin_bottom = marginBottom; this.pageSize = pageSize; this._backgroundImage = bImageDefinition; _pdfDoc = new iTextSharp.text.Document(pageSize, margin_left, margin_right, margin_top, margin_bottom); _iPDFWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(PdfDoc, stream); PdfDoc.Open(); iPDFContent = PDFWriter.DirectContent; _init(); initRow(); }
public static string PrintPDFResize(string fileNamePath) { Debug.Log("CashmaticApp", "PrintPDFResize"); string fileDirectory = Path.GetDirectoryName(fileNamePath); string fileName = Path.GetFileNameWithoutExtension(fileNamePath); string newFile = fileDirectory + "\\" + fileName + "_print.pdf"; try { // open the reader iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNamePath); iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1); //Document document = new Document(size); iTextSharp.text.Document document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(size.Width + 15, size.Height + Global.CardPaymentPrintPageSizeAddHeight)); // open the writer FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; if (Global.cardholderReceipt != "") { // select the font properties iTextSharp.text.pdf.BaseFont bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED); cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(bf, 8); int StartAt = Global.CardPaymentPrintStartAt + Global.CardPaymentPrintPageSizeAddHeight; foreach (string line in Global.cardholderReceipt.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) { // write the text in the pdf content cb.BeginText(); // put the alignment and coordinates here cb.ShowTextAligned(0, line, Global.CardPaymentPrintLeft, StartAt, 0); cb.EndText(); StartAt = StartAt - Global.CardPaymentPrintLineHeight; } } //// create the new page and add it to the pdf iTextSharp.text.pdf.PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 10, +Global.CardPaymentPrintPageSizeAddHeight); // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); } catch (Exception ex) { Debug.Log("CashmaticApp", ex.ToString()); } return(newFile); }