void CreatePdf(string input_path, IList<int> pages, string output_path) { // open a reader for the source file PdfReader reader = new PdfReader(input_path); try { reader.RemoveUnusedObjects(); // get output file using (var fs = new FileStream(output_path, FileMode.Create, FileAccess.Write)) { // create input document var input_doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(pages[0])); // create the writer PdfWriter writer = PdfWriter.GetInstance(input_doc, fs); try { writer.SetFullCompression(); input_doc.Open(); try { // for each page copy the page directly from the reader into the writer PdfContentByte cb = writer.DirectContent; foreach (int page_number in pages) { input_doc.SetPageSize(reader.GetPageSizeWithRotation(page_number)); input_doc.NewPage(); PdfImportedPage page = writer.GetImportedPage(reader, page_number); int rotation = reader.GetPageRotation(page_number); if (rotation == 90 || rotation == 270) cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(page_number).Height); else cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } finally { input_doc.Close(); } } finally { writer.Close(); } } } finally { reader.Close(); } }
private void convertJpegToPDFUsingItextSharp() { iTextSharp.text.Document Doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A2, 10, 10, 10, 10); //Store the document on the desktop string PDFOutput = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf"); PdfWriter writer = PdfWriter.GetInstance(Doc, new FileStream(PDFOutput, FileMode.Create, FileAccess.Write, FileShare.Read)); //Open the PDF for writing Doc.Open(); string Folder = "C:\\Images"; foreach (string F in System.IO.Directory.GetFiles(Folder, "*.tif")) { //Insert a page Doc.NewPage(); //Add image Doc.Add(new iTextSharp.text.Jpeg(new Uri(new FileInfo(F).FullName))); } //Close the PDF Doc.Close(); }
public static bool SaddleStitch_LayoutCroppedCoverAndInsideCover(string src, int?page_count, int?cover_length) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "ss Cover 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++) { iTextSharp.text.pdf.PdfContentByte contentbyte; if (i == 1) { docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tCover = writer.GetImportedPage(reader, i); contentbyte = writer.DirectContent; // basic positioning: need to account for page size in future // default values float x_coordinate = /*550f*/ 554.5f /*17-32 pages*/, y_coordinate = -76.25f /*48 pica*/; switch (page_count - 1 / 16) { case 0: //(01 - 16) x_coordinate = 551f; // NOT SURE ABOUT THIS ONE break; default: case 1: //(17 - 32) x_coordinate = 554.5f; // GOOD break; case 2: //(33 - 48) x_coordinate = 558f; // TESTED ON 951A, 11/17/2015 break; case 3: //(49 - 64) x_coordinate = /*558f*/ 561.5f; // GOOD break; case 4: //(65 - 80) x_coordinate = /*562f*/ 564f; break; } switch (cover_length) { default: case 48: y_coordinate = -76.25f; // GOOD break; case 49: y_coordinate = -70.5f; break; case 50: y_coordinate = -64.5f; break; case 51: y_coordinate = -58.5f; // GOOD break; } contentbyte.AddTemplate(tCover, x_coordinate, y_coordinate); } if (i == 2) { // not set up for multiple inside cover pages yet !!! docB4.NewPage(); docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tInsideCover = writer.GetImportedPage(reader, i); contentbyte = writer.DirectContent; contentbyte.AddTemplate(tInsideCover, 113f, -126f); } } docB4.Close(); reader.Close(); writer.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 static bool PerfectBind_LayoutCroppedCoverAndInsideCover(string src, int?cover_length) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "pb Cover 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++) { iTextSharp.text.pdf.PdfContentByte contentbyte; if (i == 1) { docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tCover = writer.GetImportedPage(reader, i); contentbyte = writer.DirectContent; // basic positioning: need to account for page size in future // default values: in PB briefs, y_coordinate will not vary float x_coordinate = 575.5f, y_coordinate = -76.5f; switch (cover_length) { default: case 48: // GOOD: TESTED 11/16/15 y_coordinate = -88.5f; break; case 49: // STILL AN ESTIMATE y_coordinate = -82.5f; break; case 50: // GOOD: TESTED 11/16/15 y_coordinate = -76.5f; break; case 51: // GOOD: TESTED 11/16/15 y_coordinate = -70.5f; break; } contentbyte.AddTemplate(tCover, x_coordinate, y_coordinate); } if (i == 2) { // not set up for multiple inside cover pages yet !!! docB4.NewPage(); docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tInsideCover = writer.GetImportedPage(reader, i); contentbyte = writer.DirectContent; contentbyte.AddTemplate(tInsideCover, 113f, -126f); } } docB4.Close(); reader.Close(); writer.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 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 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 string PrintLabel() { try { ShipService shpSvc = new ShipService(); ShipmentRequest shipmentRequest = new ShipmentRequest(); UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = hfLicense.Value; upss.ServiceAccessToken = upssSvcAccessToken; UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = hfUserName.Value; upssUsrNameToken.Password = hfPassword.Value; upss.UsernameToken = upssUsrNameToken; shpSvc.UPSSecurityValue = upss; RequestType request = new RequestType(); String[] requestOption = { lblAddressValidation.Text.Trim() }; request.RequestOption = requestOption; shipmentRequest.Request = request; ShipmentType shipment = new ShipmentType(); shipment.Description = "CMS Label Printing"; ShipperType shipper = new ShipperType(); shipper.ShipperNumber = hfAccountNumber.Value; PaymentInfoType paymentInfo = new PaymentInfoType(); ShipmentChargeType shpmentCharge = new ShipmentChargeType(); BillShipperType billShipper = new BillShipperType(); billShipper.AccountNumber = hfAccountNumber.Value; shpmentCharge.BillShipper = billShipper; shpmentCharge.Type = lblChargeType.Text.Trim(); ShipmentChargeType[] shpmentChargeArray = { shpmentCharge }; paymentInfo.ShipmentCharge = shpmentChargeArray; shipment.PaymentInformation = paymentInfo; UPSShipWebReference.ShipAddressType shipperAddress = new UPSShipWebReference.ShipAddressType(); String[] addressLine = { lblFromStreet.Text.Trim() }; shipperAddress.AddressLine = addressLine; shipperAddress.City = lblFromCity.Text.Trim(); shipperAddress.PostalCode = lblFromZip.Text.Trim(); shipperAddress.StateProvinceCode = hfFromStateUPSCode.Value; shipperAddress.CountryCode = hfFromCountryUPSCode.Value; shipperAddress.AddressLine = addressLine; shipper.Address = shipperAddress; shipper.Name = lblFromName.Text.Trim(); shipper.AttentionName = lblFromName.Text.Trim(); ShipPhoneType shipperPhone = new ShipPhoneType(); shipperPhone.Number = lblFromPhone.Text.Trim(); shipper.Phone = shipperPhone; shipment.Shipper = shipper; ShipFromType shipFrom = new ShipFromType(); UPSShipWebReference.ShipAddressType shipFromAddress = new UPSShipWebReference.ShipAddressType(); String[] shipFromAddressLine = { lblFromStreet.Text.Trim() }; shipFromAddress.AddressLine = addressLine; shipFromAddress.City = lblFromCity.Text.Trim(); shipFromAddress.PostalCode = lblFromZip.Text.Trim(); shipFromAddress.StateProvinceCode = hfFromStateUPSCode.Value; shipFromAddress.CountryCode = hfFromCountryUPSCode.Value; shipFrom.Address = shipFromAddress; shipFrom.AttentionName = lblFromName.Text.Trim(); shipFrom.Name = lblFromName.Text.Trim(); shipment.ShipFrom = shipFrom; ShipToType shipTo = new ShipToType(); ShipToAddressType shipToAddress = new ShipToAddressType(); String[] addressLine1 = { lblToStreet.Text.Trim() }; shipToAddress.AddressLine = addressLine1; shipToAddress.City = lblToCity.Text.Trim(); shipToAddress.PostalCode = lblToZip.Text.Trim(); shipToAddress.StateProvinceCode = hfToStateUPSCode.Value; shipToAddress.CountryCode = hfToCountryUPSCode.Value; shipTo.Address = shipToAddress; shipTo.AttentionName = lblToName.Text.Trim(); shipTo.Name = lblToName.Text.Trim(); ShipPhoneType shipToPhone = new ShipPhoneType(); shipToPhone.Number = lblToPhone.Text.Trim(); shipTo.Phone = shipToPhone; shipment.ShipTo = shipTo; ServiceType service = new ServiceType(); service.Code = lblShipService.Text.Trim(); shipment.Service = service; PackageType package = new PackageType(); PackageWeightType packageWeight = new PackageWeightType(); packageWeight.Weight = lblWeight.Text.Trim(); ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType(); uom.Code = lblMeasurementType.Text.Trim(); packageWeight.UnitOfMeasurement = uom; package.PackageWeight = packageWeight; PackagingType packType = new PackagingType(); packType.Code = lblPackagingType.Text.Trim(); package.Packaging = packType; PackageType[] pkgArray = { package }; shipment.Package = pkgArray; LabelSpecificationType labelSpec = new LabelSpecificationType(); LabelStockSizeType labelStockSize = new LabelStockSizeType(); labelStockSize.Height = "6"; labelStockSize.Width = "4"; labelSpec.LabelStockSize = labelStockSize; LabelImageFormatType labelImageFormat = new LabelImageFormatType(); labelImageFormat.Code = "GIF"; labelSpec.LabelImageFormat = labelImageFormat; shipmentRequest.LabelSpecification = labelSpec; shipmentRequest.Shipment = shipment; System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest); iTextSharp.text.Document doc = new iTextSharp.text.Document(); //Output to File string localPath = Server.MapPath("../Labels") + "\\" + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".pdf"; PdfWriter.GetInstance(doc, new FileStream(localPath, FileMode.Create)); doc.Open(); Byte[] labelBuffer = System.Convert.FromBase64String(shipmentResponse.ShipmentResults.PackageResults[0].ShippingLabel.GraphicImage); MemoryStream stream = new MemoryStream(labelBuffer); iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(stream); gif.RotationDegrees = -90f; gif.ScalePercent(50f); stream.Close(); doc.NewPage(); doc.Add(gif); doc.Close(); MemoryStream output = new MemoryStream(); doc = new iTextSharp.text.Document(); PdfWriter.GetInstance(doc, output); doc.Open(); doc.NewPage(); doc.Add(gif); doc.Close(); (new OrderEntryDAL()).UploadShippingLabel_DAL("Shipping Label", output.ToArray(), "application/pdf", shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".pdf", "", labelBuffer.Length, int.Parse(hfOrderId.Value), int.Parse(Session["UserID"].ToString())); output.Close(); return(shipmentResponse.ShipmentResults.ShipmentIdentificationNumber); } catch (System.Web.Services.Protocols.SoapException ex) { lblErr.Text = ex.Message; MPEPrepare.Show(); return(""); } catch (Exception ex) { lblErr.Text = ex.Message; MPEPrepare.Show(); return(""); } }
/// <summary> /// Generate the pdf from the images /// </summary> private void GeneratePdf() { // Create a new PDF document var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); string filename = temporaryDir + ".pdf"; var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); string[] imageFiles = Directory.GetFiles(temporaryDir); //count for progression bar CurOneStep = imageFiles.Count(); int divider; if (DataAccess.Instance.g_ReduceSize) divider = 33; else divider = 50; CurOneStep = divider / CurOneStep; //importing the images in the pdf foreach (string imageFile in imageFiles) { if (DataAccess.Instance.g_Processing) { try { //updating progress bar DataAccess.Instance.g_curProgress += CurOneStep; evnt_UpdateCurBar(); if (IsSingleFile) { DataAccess.Instance.g_totProgress = DataAccess.Instance.g_curProgress; evnt_UpdatTotBar(this, e); } //checking file extension string ext = Path.GetExtension(imageFile).ToLower(); if ((string.Compare(ext, ".jpg") == 0) || (string.Compare(ext, ".jpeg") == 0) || (string.Compare(ext, ".png") == 0) || (string.Compare(ext, ".bmp") == 0) || (string.Compare(ext, ".new") == 0)) { //var size = iTextSharp.text.PageSize.A4; var img = iTextSharp.text.Image.GetInstance(imageFile); //img.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); document.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height)); // Create an empty page document.NewPage(); img.SetAbsolutePosition(0, 0); writer.DirectContent.AddImage(img); } } catch (Exception e) { evnt_ErrorNotify(this, imageFile + " : " + e.Message.ToString()); } } } //saving file document.Close(); }
/// <summary> /// Generate the pdf from the images /// </summary> private void GeneratePdf() { // Create a new PDF document var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); string filename = temporaryDir + ".pdf"; var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); string[] imageFiles = Directory.GetFiles(temporaryDir); //count for progression bar CurOneStep = imageFiles.Count(); int divider; if (DataAccess.Instance.g_ReduceSize) { divider = 33; } else { divider = 50; } CurOneStep = divider / CurOneStep; //importing the images in the pdf foreach (string imageFile in imageFiles) { if (DataAccess.Instance.g_Processing) { try { //updating progress bar DataAccess.Instance.g_curProgress += CurOneStep; evnt_UpdateCurBar(); if (IsSingleFile) { DataAccess.Instance.g_totProgress = DataAccess.Instance.g_curProgress; evnt_UpdatTotBar(this, e); } //checking file extension string ext = Path.GetExtension(imageFile).ToLower(); if ((string.Compare(ext, ".jpg") == 0) || (string.Compare(ext, ".jpeg") == 0) || (string.Compare(ext, ".png") == 0) || (string.Compare(ext, ".bmp") == 0) || (string.Compare(ext, ".new") == 0)) { //var size = iTextSharp.text.PageSize.A4; var img = iTextSharp.text.Image.GetInstance(imageFile); //img.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); document.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height)); // Create an empty page document.NewPage(); img.SetAbsolutePosition(0, 0); writer.DirectContent.AddImage(img); } } catch (Exception e) { evnt_ErrorNotify(this, imageFile + " : " + e.Message.ToString()); } } } //saving file document.Close(); }
static void Main(string[] args) { Console.WriteLine("GVD.dat extractor for \"Ni no kuni\"\t-> by pleonex\n"); #region Get arguments if (args.Length < 3) { Show_Help(); return; } for (int i = 0; i < args.Length - 2; i++) { switch (args[i]) { // Modes case "-x": mode = 0; break; case "-en": if (i + 1 == args.Length) { Show_Help(); return; } mode = 1; // Get number of pages to extract string[] nums = args[++i].Split(','); pages_num = new int[nums.Length]; for (int n = 0; n < nums.Length; n++) { try { pages_num[n] = Convert.ToInt32(nums[n]); } catch { Show_Help(); return; } } break; case "-es": mode = 2; pages_name = args[++i].Split(','); break; // Options case "-bx": blocked = 0; break; case "-bb": blocked = 1; break; case "-bu": blocked = 2; break; case "-q": try { quality = Convert.ToInt32(args[++i]); } catch { Show_Help(); return; } break; case "-pdf": convert = 1; break; case "-nofol": nofolder = true; break; default: Show_Help(); return; } } fileIn = args[args.Length - 2]; folderOut = args[args.Length - 1]; if (!Directory.Exists(folderOut)) { Directory.CreateDirectory(folderOut); } #endregion DateTime start = DateTime.Now; // Convert to PDF, initialize it if (convert == 1) { string pdf_file = Path.Combine(folderOut, Path.GetFileNameWithoutExtension(fileIn) + ".pdf"); if (File.Exists(pdf_file)) { File.Delete(pdf_file); } pdf = new iTextSharp.text.Document(); PdfWriter.GetInstance(pdf, new FileStream(pdf_file, FileMode.Create)); pdf.Open(); pdf.AddAuthor("Studio Ghibli - Level 5"); pdf.AddTitle("Ni no kuni - Vademecum"); pdf.AddSubject("Book extracted from the PS3 version of Ni no kuni."); } // WORK! Read_BookPack(fileIn, folderOut); if (convert == 1) { if (pdf.PageNumber == 0) { pdf.NewPage(); pdf.Add(iTextSharp.text.Paragraph.GetInstance("No pages!")); } pdf.Close(); } Console.WriteLine("\nFinished in {0}!", (DateTime.Now - start).ToString()); Console.ReadKey(true); }
/// <summary> /// 引用iTextSharp.dll导出pdf数据库字典文档 /// </summary> /// <param name="databaseName"></param> /// <param name="tables"></param> public static void ExportPdfByITextSharp(string fileName, string fontPath, string databaseName, List <TableDto> tables) { // TODO 创建并添加文档信息 iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(); pdfDocument.AddTitle(fileName); iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, new System.IO.FileStream(fileName, System.IO.FileMode.Create)); pdfDocument.Open(); // 打开文档 // TODO 标题 iTextSharp.text.Paragraph title = new iTextSharp.text.Paragraph("数据库字典文档\n\n", BaseFont(fontPath, 30, iTextSharp.text.Font.BOLD)); title.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDocument.Add(title); iTextSharp.text.Paragraph subTitle = new iTextSharp.text.Paragraph(" —— " + databaseName, BaseFont(fontPath, 20, iTextSharp.text.Font.NORMAL)); subTitle.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDocument.Add(subTitle); // TODO PDF换页 pdfDocument.NewPage(); // TODO 创建添加书签章节 int chapterNum = 1; // TODO 全局字体设置,处理iTextSharp中文不识别显示问题 iTextSharp.text.Font pdfFont = BaseFont(fontPath, 12, iTextSharp.text.Font.NORMAL); // TODO log table iTextSharp.text.Chapter chapter1 = new iTextSharp.text.Chapter(new iTextSharp.text.Paragraph(AppConst.LOG_CHAPTER_NAME, pdfFont), chapterNum); pdfDocument.Add(chapter1); pdfDocument.Add(new iTextSharp.text.Paragraph("\n", pdfFont)); // 换行 CreateLogTable(pdfDocument, pdfFont, tables); // TODO PDF换页 pdfDocument.NewPage(); // TODO overview table iTextSharp.text.Chapter chapter2 = new iTextSharp.text.Chapter(new iTextSharp.text.Paragraph(AppConst.TABLE_CHAPTER_NAME, pdfFont), (++chapterNum)); pdfDocument.Add(chapter2); pdfDocument.Add(new iTextSharp.text.Paragraph("\n", pdfFont)); // 换行 CreateOverviewTable(pdfDocument, pdfFont, tables); // TODO PDF换页 pdfDocument.NewPage(); // TODO table structure // TODO 添加书签章节 iTextSharp.text.Chapter chapter3 = new iTextSharp.text.Chapter(new iTextSharp.text.Paragraph(AppConst.TABLE_STRUCTURE_CHAPTER_NAME, pdfFont), (++chapterNum)); chapter3.BookmarkOpen = true; pdfDocument.Add(chapter3); pdfDocument.Add(new iTextSharp.text.Paragraph("\n", pdfFont)); // 换行 foreach (var table in tables) { string docTableName = table.TableName + " " + (!string.IsNullOrWhiteSpace(table.Comment) ? table.Comment : ""); // TODO 添加书签章节 iTextSharp.text.Section selection = chapter3.AddSection(20f, new iTextSharp.text.Paragraph(docTableName, pdfFont), chapterNum); pdfDocument.Add(selection); pdfDocument.Add(new iTextSharp.text.Paragraph("\n", pdfFont)); // 换行 // TODO 遍历数据库表 // TODO 创建表格 iTextSharp.text.pdf.PdfPTable pdfTable = new iTextSharp.text.pdf.PdfPTable(10); // TODO 添加列标题 pdfTable.AddCell(CreatePdfPCell("序号", pdfFont)); pdfTable.AddCell(CreatePdfPCell("列名", pdfFont)); pdfTable.AddCell(CreatePdfPCell("数据类型", pdfFont)); pdfTable.AddCell(CreatePdfPCell("长度", pdfFont)); pdfTable.AddCell(CreatePdfPCell("小数位", pdfFont)); pdfTable.AddCell(CreatePdfPCell("主键", pdfFont)); pdfTable.AddCell(CreatePdfPCell("自增", pdfFont)); pdfTable.AddCell(CreatePdfPCell("允许空", pdfFont)); pdfTable.AddCell(CreatePdfPCell("默认值", pdfFont)); pdfTable.AddCell(CreatePdfPCell("列说明", pdfFont)); // TODO 添加数据行,循环数据库表字段 foreach (var column in table.Columns) { pdfTable.AddCell(CreatePdfPCell(column.ColumnOrder, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.ColumnName, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.ColumnTypeName, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.Length, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.Scale, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.IsPK, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.IsIdentity, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.CanNull, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.DefaultVal, pdfFont)); pdfTable.AddCell(CreatePdfPCell(column.Comment, pdfFont)); } // TODO 设置表格居中 pdfTable.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; pdfTable.TotalWidth = 520F; pdfTable.LockedWidth = true; pdfTable.SetWidths(new float[] { 50F, 60F, 60F, 50F, 50F, 50F, 50F, 50F, 50F, 50F }); // TODO 添加表格 pdfDocument.Add(pdfTable); // TODO PDF换页 pdfDocument.NewPage(); } // TODO 关闭释放PDF文档资源 pdfDocument.Close(); }
/// <summary> /// 把多个PDF文件、word文件、JPG/PNG/jpge图合并成一个PDF文档 /// </summary> /// <param name="fileList">需要合并文件的完整路径列表</param> /// <param name="outMergeFile">输出文件完整路径</param> /// <param name="msg">警告或错误消息</param> public void MergePDFFile(List <string> fileList, string outMergeFile, ref string msg) { PdfReader reader; PdfImportedPage newPage; PdfWriter pw; iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; iTextSharp.text.Rectangle re; foreach (var itemFile in fileList) { string fileName = Path.GetFileName(itemFile); var ext = Path.GetExtension(itemFile).ToLower(); if (!File.Exists(itemFile)) { msg += string.Format("文件打印合并__{0} 文件不存在", fileName); continue; } FileInfo fInfo = new FileInfo(itemFile); if (fInfo.Length < 1) { msg += string.Format("文件打印合并__文件内容为空,无法打印,{0}", fileName); return; } if (".pdf".Equals(ext)) { reader = new PdfReader(itemFile); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { //获取Reader的pdf页的打印方向 re = reader.GetPageSize(reader.GetPageN(j)); //设置合并pdf的打印方向 document.SetPageSize(re); document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } } else if (".doc".Equals(ext) || ".docx".Equals(ext)) { Aspose.Words.Document doc = new Aspose.Words.Document(itemFile); string newPdf = Path.GetDirectoryName(itemFile) + "\\" + Path.GetFileNameWithoutExtension(itemFile) + ".pdf"; doc.Save(newPdf, SaveFormat.Pdf); reader = new PdfReader(newPdf); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { //获取Reader的pdf页的打印方向 re = reader.GetPageSize(reader.GetPageN(j)); //设置合并pdf的打印方向 document.SetPageSize(re); document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } } else if (".jpg".Equals(ext) || ".jpeg".Equals(ext) || ".png".Equals(ext) || ".bmp".Equals(ext)) { FileStream rf = new FileStream(itemFile, FileMode.Open, FileAccess.Read); int size = (int)rf.Length; byte[] imext = new byte[size]; rf.Read(imext, 0, size); rf.Close(); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imext); //调整图片大小,使之适合A4 var imgHeight = img.Height; var imgWidth = img.Width; if (img.Height > iTextSharp.text.PageSize.A4.Height - 30) { imgHeight = iTextSharp.text.PageSize.A4.Height - 30; } if (img.Width > iTextSharp.text.PageSize.A4.Width - 30) { imgWidth = iTextSharp.text.PageSize.A4.Width - 30; } img.ScaleToFit(imgWidth, imgHeight); //调整图片位置,使之居中 img.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.NewPage(); document.Add(img); } } document.Close(); }
// public List<Card> Cards { get; set; } public void tiffToPDF(string resultPDF) { // creation of the document with a certain size and certain margins using (iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0)) { using (FileStream fs = new System.IO.FileStream(resultPDF, System.IO.FileMode.Create)) { // creation of the different writers using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs)) { document.Open(); foreach (Page page in Pages) { if (page.Card.ImageLocationLR != null) { // load the tiff image and count the total pages int total = 0; using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(page.Card.ImageLocationLR)) { total = bm2.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); // bm2 = null; bm2.Dispose(); } for (int k = 0; k < total; ++k) { System.Drawing.Bitmap bm = new System.Drawing.Bitmap(page.Card.ImageLocationLR); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp); img.ScaleToFitHeight = false; img.ScalePercent(70f / img.DpiX * 100); // scale the image to fit in the page //Lukas old value img.SetAbsolutePosition(-22, 25); img.SetAbsolutePosition(0, 0); cb.AddImage(img); document.NewPage(); img = null; cb.ClosePath(); bm.Dispose(); } } } document.Close(); document.Dispose(); writer.Dispose(); fs.Close(); fs.Dispose(); } } } }
public Boolean MergePdfFiles(String[] pdfFiles, String outputPath) { // Optional ByVal authorName As String = "", _ // Optional ByVal creatorName As String = "", _ // Optional ByVal subject As String = "", _ // Optional ByVal title As String = "", _ // Optional ByVal keywords As String = "") Boolean result = false; int pdfCount = 0; //'total input pdf file count int f = 0; //'pointer to current input pdf file string fileName = String.Empty; // 'current input pdf filename iTextSharp.text.pdf.PdfReader reader = null; int pageCount = 0; //'cureent input pdf page count iTextSharp.text.Document pdfDoc = null; // 'the output pdf document iTextSharp.text.pdf.PdfWriter writer = null; iTextSharp.text.pdf.PdfContentByte cb = null; // 'Declare a variable to hold the imported pages iTextSharp.text.pdf.PdfImportedPage page = null; int rotation = 0; bool unethicalreading = false; // 'Declare a font to used for the bookmarks iTextSharp.text.Font bookmarkFont = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE); // Try pdfCount = pdfFiles.Length; if (pdfCount > 1) { // 'Open the 1st pad using PdfReader object fileName = pdfFiles[f]; reader = new iTextSharp.text.pdf.PdfReader(fileName); // reader. iTextSharp.text.pdf.PdfReader.unethicalreading = unethicalreading; // 'Get page count pageCount = reader.NumberOfPages; // 'Instantiate an new instance of pdf document and set its margins. This will be the output pdf. // 'NOTE: bookmarks will be added at the 1st page of very original pdf file using its filename. The location // 'of this bookmark will be placed at the upper left hand corner of the document. So you'll need to adjust // 'the margin left and margin top values such that the bookmark won't overlay on the merged pdf page. The // 'unit used is "points" (72 points = 1 inch), thus in this example, the bookmarks' location is at 1/4 inch from // 'left and 1/4 inch from top of the page. pdfDoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18); // 'Instantiate a PdfWriter that listens to the pdf document writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new System.IO.FileStream(outputPath, System.IO.FileMode.Create)); //added system // 'Set metadata and open the document // With pdfDoc pdfDoc.AddAuthor(""); pdfDoc.AddCreationDate(); pdfDoc.AddCreator(""); pdfDoc.AddProducer(); pdfDoc.AddSubject(""); pdfDoc.AddTitle(""); pdfDoc.AddKeywords(""); pdfDoc.Open(); // End With // 'Instantiate a PdfContentByte object cb = writer.DirectContent; // 'Now loop thru the input pdfs while (f < pdfCount) { // 'Declare a page counter variable int i = 0; // 'Loop thru the current input pdf's pages starting at page 1 while (i < pageCount) { i += 1; // 'Get the input page size pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i)); // 'Create a new page on the output document pdfDoc.NewPage(); // 'If it is the 1st page, we add bookmarks to the page // 'If i = 1 Then // ' 'First create a paragraph using the filename as the heading // ' Dim para As New iTextSharp.text.Paragraph(IO.Path.GetFileName(fileName).ToUpper(), bookmarkFont) // ' 'Then create a chapter from the above paragraph // ' Dim chpter As New iTextSharp.text.Chapter(para, f + 1) // ' 'Finally add the chapter to the document // ' pdfDoc.Add(chpter) // 'End If // 'Now we get the imported page page = writer.GetImportedPage(reader, i); // 'Read the imported page's rotation rotation = reader.GetPageRotation(i); // 'Then add the imported page to the PdfContentByte object as a template based on the page's rotation if (rotation == 90) { cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else 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); } } //End While 2 // 'Increment f and read the next input pdf file f += 1; if (f < pdfCount) { fileName = pdfFiles[f]; reader = new iTextSharp.text.pdf.PdfReader(fileName); pageCount = reader.NumberOfPages; } // End If } //end while 1 // 'When all done, we close the document so that the pdfwriter object can write it to the output file pdfDoc.Close(); result = true; }// End If Principal // Catch ex As Exception // Throw New Exception(ex.Message) // End Try return(result); }
protected void OnButtonPDFClicked(object sender, EventArgs e) { FileChooserDialog fc= new FileChooserDialog("Укажите файл для сохранения документа", this, FileChooserAction.Save, "Отмена",ResponseType.Cancel, "Сохранить",ResponseType.Accept); fc.CurrentName = DocInfo.TypeName + " " + entryNumber.Text + ".pdf"; fc.Show(); if(fc.Run() == (int) ResponseType.Accept) { fc.Hide(); iTextSharp.text.Document document = new iTextSharp.text.Document(); using (var stream = new FileStream(fc.Filename, FileMode.Create, FileAccess.Write, FileShare.None)) { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); document.Open(); foreach(DocumentImage img in Images) { if(img.Image.Width > img.Image.Height) document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); else document.SetPageSize(iTextSharp.text.PageSize.A4); document.NewPage(); var image = iTextSharp.text.Image.GetInstance(img.file); image.SetAbsolutePosition(0,0); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); } } fc.Destroy(); }
void SavePDF() { iTextSharp.text.Document document = new iTextSharp.text.Document(); using (var stream = new MemoryStream ()) { var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); foreach(Pixbuf pix in vimageslist1.Images) { if(pix.Width > pix.Height) document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); else document.SetPageSize(iTextSharp.text.PageSize.A4); document.NewPage(); var image = iTextSharp.text.Image.GetInstance(pix.SaveToBuffer ("jpeg")); image.SetAbsolutePosition(0,0); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); stream.Position = 0; File = stream.ToArray (); } }
public static void PDF(Jądro J, Widoki.widok_matryca W, Rysowanie rys, List <string> listawybranychinformacji) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PDF file (*.pdf)|*.pdf"; // try // { if (saveFileDialog.ShowDialog() == true) { string path = System.AppDomain.CurrentDomain.BaseDirectory + "tmp"; DirectoryInfo di = Directory.CreateDirectory(path); iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); iTextSharp.text.pdf.PdfWriter wri = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(saveFileDialog.FileName, FileMode.Create)); doc.Open(); if (listawybranychinformacji[0] == "Cztery na stronę") { iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(2); iTextSharp.text.pdf.PdfPTable tableInfo = new iTextSharp.text.pdf.PdfPTable(1); if (listawybranychinformacji.Count > 1) { tableInfo = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } float[] widths = new float[] { iTextSharp.text.PageSize.A4.Width - doc.LeftMargin, iTextSharp.text.PageSize.A4.Width - doc.RightMargin }; table.SetWidths(widths); table.DefaultCell.FixedHeight = (iTextSharp.text.PageSize.A4.Height - (2 * doc.BottomMargin)) / 2; table.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Wszystkie(W, rys, true); for (int i = 0; i <= rys.liczba_matryc; i++) { iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance(System.AppDomain.CurrentDomain.BaseDirectory + "tmp\\matryca" + i + ".png"); RotationPNG(PNG); table.AddCell(PNG); if (rys.liczba_matryc + 1 % 2 != 0 && i + 1 > rys.liczba_matryc) { table.AddCell(new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(""))); } if (listawybranychinformacji.Count > 1 && i % 4 == 0) { for (int k = i; k <= i + 3; k++) { GetInfoPDF(J, k, tableInfo, listawybranychinformacji); } doc.Add(tableInfo); doc.NewPage(); tableInfo = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } if ((i % 4 == 3 && i != 0) || i + 1 > rys.liczba_matryc) { doc.Add(table); doc.NewPage(); table = new iTextSharp.text.pdf.PdfPTable(2); table.SetWidths(widths); table.DefaultCell.FixedHeight = (iTextSharp.text.PageSize.A4.Height - (2 * doc.BottomMargin)) / 2; table.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; } } } else if (listawybranychinformacji[0] == "Dwie na stronę") { iTextSharp.text.pdf.PdfPTable tableInfo = new iTextSharp.text.pdf.PdfPTable(1); iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(1); if (listawybranychinformacji.Count > 1) { tableInfo = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } float[] widths = new float[] { iTextSharp.text.PageSize.A4.Width - doc.LeftMargin }; table.SetWidths(widths); table.DefaultCell.FixedHeight = (iTextSharp.text.PageSize.A4.Height - (2 * doc.BottomMargin)) / 2; table.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Wszystkie(W, rys, true); for (int i = 0; i <= rys.liczba_matryc; i++) { iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance(System.AppDomain.CurrentDomain.BaseDirectory + "tmp\\matryca" + i + ".png"); RotationPNG(PNG); table.AddCell(PNG); if (listawybranychinformacji.Count > 1 && i % 2 == 0) { for (int k = i; k <= i + 1; k++) { GetInfoPDF(J, k, tableInfo, listawybranychinformacji); } doc.Add(tableInfo); doc.NewPage(); tableInfo = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } if (i % 2 != 0 && i != 0 || i + 1 > rys.liczba_matryc) { doc.Add(table); doc.NewPage(); table = new iTextSharp.text.pdf.PdfPTable(1); table.SetWidths(widths); table.DefaultCell.FixedHeight = (iTextSharp.text.PageSize.A4.Height - (2 * doc.BottomMargin)) / 2; table.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; } } } else if (listawybranychinformacji[0] == "Jedna na stronę") { iTextSharp.text.pdf.PdfPTable tableInfo = new iTextSharp.text.pdf.PdfPTable(1); iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(1); table.DefaultCell.FixedHeight = (iTextSharp.text.PageSize.A4.Height - (2 * doc.BottomMargin)); table.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Wszystkie(W, rys, true); if (listawybranychinformacji.Count > 1) { tableInfo = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } for (int i = 0; i <= rys.liczba_matryc; i++) { iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance(System.AppDomain.CurrentDomain.BaseDirectory + "tmp\\matryca" + i + ".png"); RotationPNG(PNG); table.AddCell(PNG); if (listawybranychinformacji.Count > 1) { GetInfoPDF(J, i, tableInfo, listawybranychinformacji); doc.Add(tableInfo); doc.NewPage(); tableInfo = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } doc.Add(table); doc.NewPage(); table = new iTextSharp.text.pdf.PdfPTable(1); table.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; } } else if (listawybranychinformacji[0] == "Brak") { if (listawybranychinformacji.Count > 1) { iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); for (int i = 0; i <= rys.liczba_matryc; i++) { GetInfoPDF(J, i, table, listawybranychinformacji); doc.Add(table); table = new iTextSharp.text.pdf.PdfPTable(listawybranychinformacji.Count - 1); } } } doc.Close(); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } di.Delete(); } // } // catch { // MessageBox.Show("Coś poszło nie tak!","Błąd!", MessageBoxButton.OK,MessageBoxImage.Warning); // } }
private void b_generate_Click(object sender, EventArgs e) //generuje pdf { float cardHeight = 0; float cardWidth = 0; float space = mm2point(float.Parse(ud_spaces.Text)); try { for (int i = 0; i < cards.Count; i++) //dodanie wartości do pól obiektów { cardHeight = mm2point((float.Parse(tb_height.Text))); cardWidth = mm2point((float.Parse(tb_width.Text))); Card k = cards[i]; k.height = cardHeight; k.width = cardWidth; cards[i] = k; } } catch (Exception ex) { MessageBox.Show("Złe wymiary karty!"); } saveFileDialog1.InitialDirectory = defaultPath; saveFileDialog1.ShowDialog(); iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 30, 30); //ustawienia dokumentu try //proba otwarcia dokumentu i zapisu w nim danych { iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.OpenOrCreate)); doc.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; int cardsInX = Convert.ToInt16((mm2point(210) + space - doc.LeftMargin - doc.RightMargin) / (cardWidth + space)); int cardsInY = Convert.ToInt16((mm2point(297) + space - doc.BottomMargin - doc.TopMargin) / (cardHeight + space)); float reverse_margin = mm2point(210) + space - cardsInX * (cardWidth + space) - doc.LeftMargin; int x = 0; int y = 0; int a = (cards.Count - (cards.Count % (cardsInX * cardsInY))); List<Card> temp = new List<Card>(); doc.NewPage(); for (int i = 0; i < cards.Count; i++) //dla każdej karty dodajemy do dokumentu jego front na pierwszej stronie { var img = iTextSharp.text.Image.GetInstance(cards[i].frontPath); img.SetAbsolutePosition(doc.LeftMargin + x * (cards[i].width + space), doc.BottomMargin + y * (cards[i].height + space)); if (Image.FromFile(cards[i].frontPath).Height > Image.FromFile(cards[i].frontPath).Width) { img.ScaleAbsolute(cardWidth, cardHeight); } else { img.RotationDegrees = 90; img.ScaleAbsolute(cardHeight, cardWidth); } cb.AddImage(img); temp.Add(cards[i]); x++; if (x >= cardsInX && i != cards.Count - 1) //jesli fronty kart nie mieszcza sie na kartce w osi X { x = 0; y++; if (y >= cardsInY) //jesli fronty kart nie mieszcza sie na kartce w osi Y, czyli gdy strona zostanie przepelniona { y = 0; doc.NewPage(); for (int z = 0; z < temp.Count; z++) //tworzona jest kolejna strona i dodawane sa na niej rewersy { var reverse = iTextSharp.text.Image.GetInstance(temp[z].reversePath); reverse.SetAbsolutePosition((mm2point(210) - doc.LeftMargin - temp[z].width - x * (temp[z].width + space)), doc.BottomMargin + y * (temp[z].height + space)); if (Image.FromFile(cards[i].reversePath).Height > Image.FromFile(cards[i].reversePath).Width) { reverse.ScaleAbsolute(cardWidth, cardHeight); } else { reverse.RotationDegrees = 90; reverse.ScaleAbsolute(cardHeight, cardWidth); } cb.AddImage(reverse); x++; if (x >= cardsInX) { x = 0; y++; if (y >= cardsInY) { y = 0; doc.NewPage(); break; } } } temp.Clear(); } } else if (i >= a && i == cards.Count - 1) //gdy aktualna strona jest niezapelniona i przeanalizowalismy ostatnia karte - tworzy dodatkowa strone z rewersami (bo wtedy w pierwszy if w ogole program nie wchodzi) { doc.NewPage(); y = 0; x = 0; for (int z = 0; z < temp.Count; z++) { var reverse = iTextSharp.text.Image.GetInstance(temp[z].reversePath); reverse.SetAbsolutePosition((mm2point(210) - doc.LeftMargin - temp[z].width - x * (temp[z].width + space)), doc.BottomMargin + y * (temp[z].height + space)); reverse.ScaleAbsolute(cardWidth, cardHeight); cb.AddImage(reverse); x++; if (x >= cardsInX) { x = 0; y++; if (y >= cardsInY) { y = 0; doc.NewPage(); break; } } } } } doc.Close(); MessageBox.Show("Plik pdf został utworzony!"); } catch (Exception ex) { MessageBox.Show("Utworzenie pliku nie powiodło się."); } }
/// <summary> /// 把图表转成图片 /// </summary> /// <param name="context"></param> public void SaveImage(HttpContext context) { if (context.Request.Form["svg"] != null) { string tType = "image/png"; string tSvg = context.Request.Form["svg"].ToString(); string tFileName = ""; Random rand = new Random(24 * (int)DateTime.Now.Ticks); tFileName = rand.Next().ToString(); MemoryStream tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg)); MemoryStream tStream = new MemoryStream(); string tTmp = new Random().Next().ToString(); string tExt = ""; string tTypeString = ""; switch (tType) { case "image/png": tTypeString = "-m image/png"; tExt = "png"; break; case "image/jpeg": tTypeString = "-m image/jpeg"; tExt = "jpg"; break; case "application/pdf": tTypeString = "-m application/pdf"; tExt = "pdf"; break; case "image/svg+xml": tTypeString = "-m image/svg+xml"; tExt = "svg"; break; } if (tTypeString != "") { //string tWidth = context.Request.Form["width"].ToString(); //string tWidth = "0"; Svg.SvgDocument tSvgObj = SvgDocument.Open(tData); switch (tExt) { case "jpg": tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg); break; case "png": tSvgObj.Draw().Save(tStream, ImageFormat.Png); break; case "pdf": PdfWriter tWriter = null; iTextSharp.text.Document tDocumentPdf = null; try { tSvgObj.Draw().Save(tStream, ImageFormat.Png); tDocumentPdf = new iTextSharp.text.Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height)); tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f); iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(tStream.ToArray()); tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height); tStream = new MemoryStream(); tWriter = PdfWriter.GetInstance(tDocumentPdf, tStream); tDocumentPdf.Open(); tDocumentPdf.NewPage(); tDocumentPdf.Add(tGraph); tDocumentPdf.CloseDocument(); } catch (Exception ex) { throw ex; } finally { tDocumentPdf.Close(); tDocumentPdf.Dispose(); tWriter.Close(); tWriter.Dispose(); tData.Dispose(); tData.Close(); } break; case "svg": tStream = tData; break; } System.IO.MemoryStream ms = new System.IO.MemoryStream(tStream.ToArray()); System.Drawing.Image image = System.Drawing.Image.FromStream(ms); string savePath = context.Server.MapPath("image/"); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } savePath += tFileName + "." + tExt; string SavePathImage = tFileName + "." + tExt; context.Session["FirstImage"] = savePath; image.Save(savePath, System.Drawing.Imaging.ImageFormat.Png); image.Dispose(); context.Response.Write(tFileName + "." + tExt); } } }
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); } }
public static void CreatePDF(string filePath, string destinationfilePath) { string directoryPath = Path.GetDirectoryName(destinationfilePath); string filename = Path.GetFileNameWithoutExtension(destinationfilePath); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); try { var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(Path.Combine(directoryPath, filename) + ".pdf", FileMode.Create)); document.Open(); iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(); paragraph.Alignment = iTextSharp.text.Element.ALIGN_LEFT; var extension = Path.GetExtension(filePath); switch (extension.ToLower()) { case ".jpg": case ".bmp": case ".jpeg": case ".gif": case ".png": case ".tiff": iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(Image.FromFile(filePath), GetImageFormat(UserArgs.Configurations.ImageFormat)); pic.Border = 1; pic.BorderColor = iTextSharp.text.BaseColor.BLACK; paragraph.Add(pic); document.Add(paragraph); document.NewPage(); break; case ".txt": paragraph.Add(File.ReadAllText(filePath)); document.Add(paragraph); document.NewPage(); break; case ".htm": case ".html": TextReader reader = new StringReader(File.ReadAllText(filePath)); HTMLWorker worker = new HTMLWorker(document); worker.StartDocument(); worker.Parse(reader); worker.EndDocument(); worker.Close(); break; case ".rtf": string htmlDocument = GetHtmlFromRTF(File.ReadAllText(filePath)); reader = new StringReader(htmlDocument); worker = new HTMLWorker(document); worker.StartDocument(); worker.Parse(reader); worker.EndDocument(); worker.Close(); break; default: paragraph.Add(File.ReadAllText(filePath)); document.Add(paragraph); document.NewPage(); break; } } catch (iTextSharp.text.DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); }
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); }
/// <summary> /// Merge CV and covering letter and return pdf location /// </summary> /// <param name="filesToMerge"></param> /// <param name="outputFilename"></param> /// <param name="result"></param> public static void MergePdf(IEnumerable<BulkPrintDocEntry> filesToMerge, string outputFilename, ref BulkPrintCvResult result) { result.ErrorCvs = new List<BulkPrintErrorCvs>(); var bulkPrintDocEntries = filesToMerge as BulkPrintDocEntry[] ?? filesToMerge.ToArray(); if (!bulkPrintDocEntries.Any()) return; var document = new iTextSharp.text.Document(); // initialize pdf writer var writer = PdfWriter.GetInstance(document, new FileStream(outputFilename, FileMode.Create)); // open document to write document.Open(); var content = writer.DirectContent; foreach (var docEntry in bulkPrintDocEntries) { var sCoveringLetterHtml = docEntry.CoveringLetterHtml; // create page document.NewPage(); // add styles var styles = new StyleSheet(); styles.LoadStyle("left", "width", "22%"); styles.LoadTagStyle("td", "valign", "top"); styles.LoadStyle("bordered", "border", "1"); var hw = new HTMLWorker(document, null, styles); hw.Parse(new StringReader(sCoveringLetterHtml)); var sFileName = docEntry.CvFileName.ToLower().Replace(".docx", ".pdf").Replace(".DOCX", ".pdf").Replace(".doc", ".pdf").Replace(".DOC", ".pdf").Replace(".rtf", ".pdf").Replace(".RTF", ".pdf"); if (!File.Exists(sFileName)) { //pdf file not exists result.ErrorCvs.Add(new BulkPrintErrorCvs { Error = "Pdf file does not exists. " + sFileName, ContactId = docEntry.ContactId, ContactName = new Contacts().GetCandidateName(docEntry.ContactId), Document = docEntry.Doc }); continue; } // Create pdf reader var reader = new PdfReader(sFileName); if (!reader.IsOpenedWithFullPermissions) { //pdf file does not have permission result.ErrorCvs.Add(new BulkPrintErrorCvs { Error = "Do not have enough permissions to read the file", ContactId = docEntry.ContactId, ContactName = new Contacts().GetCandidateName(docEntry.ContactId), Document = docEntry.Doc }); continue; } var numberOfPages = reader.NumberOfPages; // Iterate through all pages for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { // Determine page size for the current page document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex)); // Create page document.NewPage(); var importedPage = writer.GetImportedPage(reader, currentPageIndex); // Determine page orientation var pageOrientation = reader.GetPageRotation(currentPageIndex); switch (pageOrientation) { case 90: content.AddTemplate(importedPage, 0, -1, 1, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height); break; case 270: content.AddTemplate(importedPage, 0, 1, -1, 0, reader.GetPageSizeWithRotation(currentPageIndex).Width, 0); break; default: content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0); break; } } } document.Close(); }
public static void SaveImages(List<ParsedImage> images, string outputFile) { var doc = new iTextSharp.text.Document(); try { var writer = PdfWriter.GetInstance(doc, new FileStream(outputFile, FileMode.Create)); writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5); writer.CompressionLevel = PdfStream.BEST_COMPRESSION; doc.Open(); foreach (var parsedImage in images) { var image = iTextSharp.text.Image.GetInstance(parsedImage.Image, parsedImage.Format); var width = parsedImage.Width; var height = parsedImage.Height; if ((parsedImage.PerformedRotation == RotateFlipType.Rotate90FlipNone) || (parsedImage.PerformedRotation == RotateFlipType.Rotate270FlipNone)) { var temp = width; width = height; height = temp; } var size = new iTextSharp.text.Rectangle(width, height); image.ScaleAbsolute(width, height); image.CompressionLevel = PdfStream.BEST_COMPRESSION; doc.SetPageSize(size); doc.NewPage(); image.SetAbsolutePosition(0, 0); doc.Add(image); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { doc.Close(); } }
private void AddCartaoSUSCompleto(long numeroCartaoSUS) { ISeguranca iseguranca = Factory.GetInstance<ISeguranca>(); if (!iseguranca.VerificarPermissao(((ViverMais.Model.Usuario)Session["Usuario"]).Codigo, "ALTERAR_CARTAO_SUS", Modulo.CARTAO_SUS)) { ClientScript.RegisterClientScriptBlock(typeof(String), "ok", "<script>alert('Você não tem permissão para acessar essa página. Em caso de dúViverMais, entre em contato.');window.location='../Home.aspx';</script>"); return; } MemoryStream MStream = new MemoryStream(); iTextSharp.text.Document doc = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(295, 191)); PdfWriter writer = PdfWriter.GetInstance(doc, MStream); //Monta o pdf doc.Open(); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.IndentationLeft = -10; p.Font.Color = iTextSharp.text.Color.BLACK; iTextSharp.text.Phrase nome = new iTextSharp.text.Phrase(HiddenNomePaciente.Value + "\n"); //paciente.Nome nome.Font.Size = 8; iTextSharp.text.Phrase nascimento = new iTextSharp.text.Phrase(HiddenDataNascimento.Value + "\t\t" + HiddenMunicipio.Value + "\n"); nascimento.Font.Size = 8; iTextSharp.text.Phrase cartaosus = new iTextSharp.text.Phrase(numeroCartaoSUS + "\n"); cartaosus.Font.Size = 12; PdfContentByte cb = writer.DirectContent; Barcode39 code39 = new Barcode39(); code39.Code = numeroCartaoSUS.ToString(); code39.StartStopText = true; code39.GenerateChecksum = false; code39.Extended = true; iTextSharp.text.Image imageEAN = code39.CreateImageWithBarcode(cb, null, null); iTextSharp.text.Image back = iTextSharp.text.Image.GetInstance(Server.MapPath("img/") + "back_card.JPG"); back.SetAbsolutePosition(0, doc.PageSize.Height - back.Height); iTextSharp.text.Image front = iTextSharp.text.Image.GetInstance(Server.MapPath("img/") + "front_card.JPG"); front.SetAbsolutePosition(0, doc.PageSize.Height - front.Height); iTextSharp.text.Phrase barcode = new iTextSharp.text.Phrase(new iTextSharp.text.Chunk(imageEAN, 36, -45)); barcode.Font.Color = iTextSharp.text.Color.WHITE; p.SetLeading(1, 0.7f); p.Add(cartaosus); p.Add(nome); p.Add(nascimento); p.Add(barcode); doc.Add(p); doc.Add(back); doc.NewPage(); doc.Add(front); doc.Close(); //Fim monta pdf HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=CartaoSUS.pdf"); HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer()); HttpContext.Current.Response.End(); }