//srcで指定されたPDFファイルをページ毎に分割し、destで指定されたパスに保存する。 //保存ファイル名は「ファイル名-ページ番号.pdf」とする。 //分割したページ数を返す。 public List<string> Run(string src, string dest) { // srcで渡されたファイルが存在するか? if (!File.Exists(src)) { throw new FileNotFoundException(); } // destで渡されたフォルダが存在するか? if (!Directory.Exists(dest)) { throw new DirectoryNotFoundException(); } var reader = new iTextSharp.text.pdf.PdfReader(src); string file_name = Path.GetFileNameWithoutExtension(src); int digit = reader.NumberOfPages.ToString().Length; var app_name = new MainForm(); // 一時フォルダにpdfを作成してdestにコピー。 // その際上書き確認を行う。 System.IO.DirectoryInfo del = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text); if (del.Exists) del.Delete(true); System.IO.DirectoryInfo tmp = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text); tmp.Create(); for (int i = 1; i <= reader.NumberOfPages; i++) { var doc = new iTextSharp.text.Document(); var dest_tmp = String.Format(@"{{0}}\{{1}}-{{2:D{0}}}.pdf", digit); var dest_name = String.Format(dest_tmp, tmp, file_name, i); var copy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(dest_name, FileMode.Create)); doc.Open(); copy.AddPage(copy.GetImportedPage(reader, i)); doc.Close(); } // コピーしたファイルを監視する Ret.list.Clear(); var watcher = new System.IO.FileSystemWatcher(); watcher.Path = dest; watcher.Filter = "*.pdf"; watcher.Changed += new FileSystemEventHandler(changed); watcher.Created += new FileSystemEventHandler(changed); watcher.EnableRaisingEvents = true; FileSystem.CopyDirectory(tmp.ToString(), dest, UIOption.AllDialogs); watcher.EnableRaisingEvents = false; watcher.Dispose(); watcher = null; tmp.Delete(true); reader.Close(); return Ret.list; }
/* ----------------------------------------------------------------- */ /// /// CreateFromImage /// /// <summary> /// 画像ファイルから PdfReader オブジェクトを生成します。 /// </summary> /// /// <param name="src">画像ファイルのパス</param> /// <param name="io">入出力用オブジェクト</param> /// /// <returns>PdfReader オブジェクト</returns> /// /* ----------------------------------------------------------------- */ public static PdfReader CreateFromImage(string src, IO io) { using (var ms = new System.IO.MemoryStream()) using (var ss = io.OpenRead(src)) using (var image = Image.FromStream(ss)) { Debug.Assert(image != null); Debug.Assert(image.FrameDimensionsList != null); Debug.Assert(image.FrameDimensionsList.Length > 0); var doc = new iTextSharp.text.Document(); var writer = PdfWriter.GetInstance(doc, ms); doc.Open(); var guid = image.FrameDimensionsList[0]; var dim = new FrameDimension(guid); for (var i = 0; i < image.GetFrameCount(dim); ++i) { image.SelectActiveFrame(dim, i); var scale = PdfFile.Point / image.HorizontalResolution; var w = image.Width * scale; var h = image.Height * scale; doc.SetPageSize(new iTextSharp.text.Rectangle(w, h)); doc.NewPage(); doc.Add(image.GetItextImage()); } doc.Close(); writer.Close(); return(new PdfReader(ms.ToArray())); } }
private static void MergeFiles(string destinationFile, string ExportPath) { #region new code using (FileStream stream = new FileStream(destinationFile, FileMode.Create)) { iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); iTextSharp.text.pdf.PdfCopy pdf = new iTextSharp.text.pdf.PdfCopy(pdfDoc, stream); pdfDoc.Open(); var files = Directory.GetFiles(ExportPath); int i = 1; foreach (string file in files) { // MemoryStream content= new MemoryStream( var reader = new iTextSharp.text.pdf.PdfReader(file); pdf.AddDocument(reader); i++; reader.Close(); } if (pdfDoc != null) { pdfDoc.Close(); } } #endregion }
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(); } }
/// <summary> /// 返回页数 PdfReader /// </summary> /// <param name="outMergeFile"></param> /// <returns></returns> public int MergePDFFilesPages(string outMergeFile) { int page = 0; PdfReader reader; try { using (iTextSharp.text.Document document = new iTextSharp.text.Document()) { if (File.Exists(outMergeFile)) { reader = new PdfReader(outMergeFile); if (reader != null) { page = reader.NumberOfPages; reader.Close(); reader.Dispose(); } } document.Close(); document.Dispose(); File.SetAttributes(outMergeFile, FileAttributes.Normal); } return(page); } catch (Exception ex) { MyCommon.WriteLog("取PDF页数报错" + ex.Message); return(page); } }
/// <summary> /// Rubber stamps an image based PDF as a PDF/A-1B pdf. /// </summary> /// <param name="oldFile">The original pdf file.</param> /// <param name="newFile">The new pdf file.</param> public void ConvertPDF(FileInfo oldFile, FileInfo newFile) { using (FileStream fs = new FileStream(newFile.FullName, FileMode.Create, FileAccess.Write)) using (PdfReader pdf = new PdfReader(oldFile.FullName)) using (iTextSharp.text.Document doc = new iTextSharp.text.Document(pdf.GetPageSizeWithRotation(1))) using (PdfAWriter writer = PdfAWriter.GetInstance(doc, fs, PdfAConformanceLevel.PDF_A_1B)) { doc.Open(); ICC_Profile icc = ICC_Profile.GetInstance(Environment.GetEnvironmentVariable("SystemRoot") + @"\System32\spool\drivers\color\sRGB Color Space Profile.icm"); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); PdfContentByte contentByte = writer.DirectContent; for (int i = 1; i <= pdf.NumberOfPages; i++) { doc.SetPageSize(pdf.GetPageSizeWithRotation(i)); doc.NewPage(); PdfImportedPage page = writer.GetImportedPage(pdf, i); contentByte.AddTemplate(page, 0, 0); } writer.CreateXmpMetadata(); doc.Close(); } OnPdfConverted(oldFile); }
public void MergePDFs(string outPutFilePath, params string[] filesPath) { try { List <PdfReader> readerList = new List <PdfReader>(); foreach (string filePath in filesPath) { PdfReader pdfReader = new PdfReader(filePath); readerList.Add(pdfReader); } iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0f, 0f, 0f, 20f); iTextSharp.text.pdf.PdfCopy writer = new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(outPutFilePath, System.IO.FileMode.Create)); document.Open(); foreach (PdfReader reader in readerList) { for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); document.Add(iTextSharp.text.Image.GetInstance(page)); } writer.AddDocument(reader); reader.Close(); } document.Close(); writer.Close(); } catch (Exception ex) { ex.ToString(); } }
private void btnSave_Click(object sender, EventArgs e) { //saving the reciepts into pdf format for expenses using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate()); try { PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create)); doc.Open(); doc.Add(new iTextSharp.text.Paragraph(rtLoanreciept1.Text)); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { doc.Close(); } } } }
public static MemoryStream CreatePdfDoc(List <MemoryStream> memoryStreamPdfStamperList) { iTextSharp.text.Document document = new iTextSharp.text.Document(); if (memoryStreamPdfStamperList.Count > 0) { document = new iTextSharp.text.Document(iTextSharp.text.PageSize.B8); } MemoryStream memoryStreamDocument = new MemoryStream(); PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStreamDocument); document.Open(); pdfWriter.CloseStream = false; foreach (MemoryStream memoryStreamPdfStamper in memoryStreamPdfStamperList) { PdfContentByte pdfContentByte = pdfWriter.DirectContent; document.NewPage(); PdfImportedPage pdfImportedPage = pdfWriter.GetImportedPage(new PdfReader(memoryStreamPdfStamper.GetBuffer()), 1); pdfContentByte.AddTemplate(pdfImportedPage, 0, 0); //const float posX = 20f; //const float posY = 30f; //pdfContentByte.AddTemplate(pdfImportedPage, posX, posY); memoryStreamPdfStamper.Dispose(); } document.Close(); return(memoryStreamDocument); }
private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage, int endpage) { PdfReader reader = null; iTextSharp.text.Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; PdfReader.unethicalreading = true; reader = new PdfReader(sourcePDFpath); sourceDocument = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(startpage)); pdfCopyProvider = new PdfCopy(sourceDocument, new FileStream(outputPDFpath, FileMode.Create)); sourceDocument.Open(); for (int i = startpage; i < startpage + endpage; i++) { Application.DoEvents(); try { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } catch (ArgumentException ex) { throw ex; } } sourceDocument.Close(); reader.Close(); }
/// <summary> 合併PDF(集合) </summary> /// <param name="fileList">欲合併PDF檔之集合(一筆以上)</param> /// <param name="outMergeFile">合併後的檔名</param> private byte[] MergePDFFiles(List <byte[]> fileList, string outMergeFile) { outMergeFile = Server.MapPath(outMergeFile); PdfReader reader; iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage newPage; for (int i = 0; i < fileList.Count; i++) { // reader = new PdfReader(Server.MapPath(fileList[i])); reader = new PdfReader(fileList[i]); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } } document.Close(); return(cb.ToPdf(writer)); }
private void comPDF(List <string> filelist, string path0) { PdfReader reader; List <PdfReader> readerList = new List <PdfReader>(); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path0, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage newPage; for (int i = 0; i < filelist.Count; i++) { reader = new PdfReader(filelist[i]); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } readerList.Add(reader); } document.Close(); foreach (var rd in readerList)//清理占用 { rd.Dispose(); } }
private void Button_Click_3(object sender, RoutedEventArgs e) { using (var ms = new MemoryStream()) { var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0); iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression(); document.Open(); foreach (System.Drawing.Image aa in obj) { MemoryStream msimage = new MemoryStream(); aa.Save(msimage, ImageFormat.Jpeg); var image = iTextSharp.text.Image.GetInstance(msimage.ToArray()); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); string Path = ConfigurationManager.AppSettings["uploadfolderpath"].ToString(); string filename = "C3kycDMS" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".pdf"; File.WriteAllBytes(Path + filename, ms.ToArray()); byte[] test = ms.ToArray(); MessageBox.Show("File Uploaded Successfully", "Success!", MessageBoxButton.OKCancel); pic_scan.Source = null; } }
public static void AddPic(iTextSharp.text.Document document, string imagefile, int chartid, Canvas canvas) { ImageFromPieControl(imagefile, chartid, canvas); iTextSharp.text.Image pdfimage = iTextSharp.text.Image.GetInstance(imagefile); pdfimage.SetDpi(300, 300); float left = 425; if (chartid == 2) { pdfimage.ScaleAbsolute(120, 120 * (550f / 350f)); left = 440; } else { pdfimage.ScaleToFit(140, 140); } float y = 0; switch (chartid) { case 0: y = 600; break; case 1: y = 365; break; case 2: y = 45; break; } pdfimage.SetAbsolutePosition(left, y); document.Add(pdfimage); }
public static void pdfMain(string[] args, string strFileName) { int ishave = 0; string[] files = { @"D:\Devlop\PIC_control\PicFile_Managerment\PicFile_Managerment\bin\Debug\FileList\0x1024a0a0.jpg", @"D:\Devlop\PIC_control\PicFile_Managerment\PicFile_Managerment\bin\Debug\FileList\1.jpg" }; files = args; iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); try { iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create, FileAccess.ReadWrite)); document.Open(); iTextSharp.text.Image image; for (int i = 0; i < files.Length; i++) { if (String.IsNullOrEmpty(files[i])) { break; } if (File.Exists(files[i])) { image = iTextSharp.text.Image.GetInstance(files[i]); } else { continue; } if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.NewPage(); document.Add(image); ishave++; //iTextSharp.text.Chunk c1 = new iTextSharp.text.Chunk("Hello World"); //iTextSharp.text.Phrase p1 = new iTextSharp.text.Phrase(); //p1.Leading = 150; //行间距 //document.Add(p1); } Console.WriteLine("转换成功!"); } catch (Exception ex) { Console.WriteLine("转换失败,原因:" + ex.Message); } if (ishave != 0) { document.Close(); } //Console.ReadKey(); }
private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage, int endpage) { Console.WriteLine("Extracting document " + DateTime.Now.Millisecond); PdfReader reader = null; iTextSharp.text.Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; PdfReader.unethicalreading = true; reader = new PdfReader(sourcePDFpath); sourceDocument = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(startpage)); pdfCopyProvider = new PdfCopy(sourceDocument, new FileStream(outputPDFpath, FileMode.Create)); sourceDocument.Open(); for (int i = startpage; i < startpage + endpage; i++) { try { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } catch (System.ArgumentException ex) { throw ex; } } sourceDocument.Close(); reader.Close(); }
private System.IO.MemoryStream reorderSaddleStitchBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); var order = new SaddleStitchPageOrder(reader.NumberOfPages); reader.SelectPages(order.PageOrder); var pdfdoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); var pdfcopy_provider = new iTextSharp.text.pdf.PdfCopy(pdfdoc, dest_stream); pdfdoc.Open(); iTextSharp.text.pdf.PdfImportedPage importedPage; for (int i = 1; i <= reader.NumberOfPages; i++) { importedPage = pdfcopy_provider.GetImportedPage(reader, i); pdfcopy_provider.AddPage(importedPage); } pdfdoc.Close(); reader.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
/// <summary> /// Creates a PDF from html string /// </summary> /// <param name="htmlContent">The HTML content to be converted</param> /// <param name="pageSize">The size of the output page</param> /// <returns></returns> public MemoryStream CreatePDFFromHtml(string htmlContent, iTextSharp.text.Rectangle pageSize) { MemoryStream ms = new MemoryStream(); //Step 1: Create a Docuement-Object iTextSharp.text.Document document = new iTextSharp.text.Document(pageSize); //Step 2: we create a writer that listens to the document iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms); //Step 3: Open the document document.Open(); // Add a new page to the pdf file document.NewPage(); //make an arraylist ....with STRINGREADER since its no IO reading file... List <iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlContent), null); //add the collection to the document for (int k = 0; k < htmlarraylist.Count; k++) { document.Add((iTextSharp.text.IElement)htmlarraylist[k]); } document.Close(); return(ms); }
public static bool SaddleStitch_ReorderPagesForLayout(string src) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "ss brief reordered.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); SaddleStitchPageOrder order = new SaddleStitchPageOrder(reader.NumberOfPages); reader.SelectPages(order.PageOrder); iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); iTextSharp.text.pdf.PdfCopy pdfcopy_provider = new iTextSharp.text.pdf.PdfCopy(pdfdoc, stream); pdfdoc.Open(); iTextSharp.text.pdf.PdfImportedPage importedPage; for (int i = 1; i <= reader.NumberOfPages; i++) { importedPage = pdfcopy_provider.GetImportedPage(reader, i); pdfcopy_provider.AddPage(importedPage); } pdfdoc.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 static string SavePDF(string strInputFile, string strOutputFile) { iTextSharp.text.Document doc = null; try { iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(strInputFile); iTextSharp.text.Rectangle rectDocSize = new iTextSharp.text.Rectangle(img.Width, img.Height); doc = new iTextSharp.text.Document(rectDocSize); iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(strOutputFile, FileMode.Create)); doc.Open(); //doc.Add(new iTextSharp.text.Paragraph("GIF")); doc.Add(img); } catch (iTextSharp.text.DocumentException dex) { throw dex; } catch (IOException ioex) { throw ioex; } catch (Exception ex) { throw ex; } finally { if(doc != null) doc.Close(); } return strOutputFile; }
public static bool CombineCoverAndInsideCover(List <CockleFilePdf> files, string src) { try { using (var stream = new System.IO.FileStream(src, System.IO.FileMode.Create)) { // initiate iTextSharp processes iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); iTextSharp.text.pdf.PdfCopy pdfcopy = new iTextSharp.text.pdf.PdfCopy(pdfdoc, stream); pdfdoc.Open(); // merge pdfs in folder CockleFilePdf f; for (int i = 0; i < files.Count; i++) { f = files[i]; // read file iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(f.FullName); int filePageCount = reader.NumberOfPages; pdfcopy.AddDocument(new iTextSharp.text.pdf.PdfReader(reader)); } pdfcopy.Close(); pdfdoc.CloseDocument(); } return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
public static string SavePDF(string strInputFile, string strOutputFile) { iTextSharp.text.Document doc = null; try { iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(strInputFile); iTextSharp.text.Rectangle rectDocSize = new iTextSharp.text.Rectangle(img.Width, img.Height); doc = new iTextSharp.text.Document(rectDocSize); iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(strOutputFile, FileMode.Create)); doc.Open(); //doc.Add(new iTextSharp.text.Paragraph("GIF")); doc.Add(img); } catch (iTextSharp.text.DocumentException dex) { throw dex; } catch (IOException ioex) { throw ioex; } catch (Exception ex) { throw ex; } finally { if (doc != null) { doc.Close(); } } return(strOutputFile); }
public void VbExportPdf(GridView argsGrid, string argsFileName, string argsTitle) { HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + argsFileName.Trim() + ".pdf"); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); var sw = new StringWriter(); var hw = new HtmlTextWriter(sw); argsGrid.HeaderRow.Style.Add("background-color", "gray"); if (!string.IsNullOrEmpty(argsTitle)) { var lblTitle = new Label { Text = argsTitle }; lblTitle.RenderControl(hw); } argsGrid.RenderControl(hw); var sr = new StringReader(sw.ToString()); var pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A2, 7f, 7f, 7f, 0f); var htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); HttpContext.Current.Response.Write(pdfDoc); HttpContext.Current.Response.End(); }
void ConvertJPG2PDF(string jpgfile, string pdf) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); using (Stream stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) { PdfWriter.GetInstance(document, stream); document.Open(); using (FileStream imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); } document.Close(); } }
private System.IO.MemoryStream joinTwoStreamsIntoOnePdf(System.IO.MemoryStream stream_1, System.IO.MemoryStream stream_2) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var doc = new iTextSharp.text.Document(); var writer = new iTextSharp.text.pdf.PdfCopy(doc, dest_stream); doc.Open(); var reader_1 = new iTextSharp.text.pdf.PdfReader(stream_1.ToArray()); for (var i = 1; i <= reader_1.NumberOfPages; i++) { var page = writer.GetImportedPage(reader_1, i); writer.AddPage(page); } reader_1.Close(); var reader_2 = new iTextSharp.text.pdf.PdfReader(stream_2.ToArray()); for (var i = 1; i <= reader_2.NumberOfPages; i++) { var page = writer.GetImportedPage(reader_2, i); writer.AddPage(page); } reader_2.Close(); doc.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
private byte[] ConvertJPG2PDF(Stream imageStream) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); MemoryStream memStream = new MemoryStream(); PdfWriter wr = PdfWriter.GetInstance(document, memStream); document.Open(); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); document.Close(); return(memStream.ToArray()); }
static void MergePdfFiles(string foldernameInput, string folderNameOutput) { var files = Directory.GetFiles(foldernameInput, "*.pdf"); int count = 0; foreach (var file in files) { var pdfReader = new iTextSharp.text.pdf.PdfReader(file); var pdfDoc = new iTextSharp.text.Document(pdfReader.GetPageSizeWithRotation(1)); // 'Instantiate a PdfWriter that listens to the pdf document var outputfile = Path.Combine(folderNameOutput, Path.GetFileName(file)); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(outputfile, FileMode.Create)); pdfDoc.Open(); int pagenumber = 0; int pagecount = pdfReader.NumberOfPages; var cb = writer.DirectContent; while (pagenumber < pagecount) { pdfDoc.NewPage(); var importedPage = writer.GetImportedPage(pdfReader, pagenumber + 1); writer.DirectContentUnder.AddTemplate(importedPage, 0, 0); if (pagenumber == 0) { CopyFormToText(pdfReader, cb); } pagenumber++; } writer.Flush(); pdfDoc.Close(); count++; } }
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"); } }
private void Html2Pdf(string htmlData, string pdfFilename) { using (MemoryStream ms = new MemoryStream()) using (TextReader textReader = new StringReader(htmlData)) { iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms); pdfWriter.CloseStream = false; // say to PdfWriter: do not close the MemoryStream HTMLWorker htmlWorker = new HTMLWorker(document); document.Open(); htmlWorker.StartDocument(); htmlWorker.Parse(textReader); htmlWorker.EndDocument(); htmlWorker.Close(); document.Close(); ms.Position = 0; // reset position for further read using (FileStream fs = System.IO.File.OpenWrite(pdfFilename)) { using (ms) { ms.WriteTo(fs); } } } }
public static void CreatePDF(Image image, string filePath, ImageFormat format) { string directoryPath = Path.GetDirectoryName(filePath); string filename = Path.GetFileNameWithoutExtension(filePath); 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.Image pic = iTextSharp.text.Image.GetInstance(image, format); iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(); pic.Border = 1; pic.BorderColor = iTextSharp.text.BaseColor.BLACK; paragraph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; paragraph.Add(pic); document.Add(paragraph); document.NewPage(); } catch (iTextSharp.text.DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); }
/// <summary> /// Start new form generation with out to stream /// </summary> /// <param name="Output PDF file name"></param> /// <returns></returns> public bool Create() { inFileStream = null; outFileStream = null; m_pdfReader = null; m_stamper = null; try { values = null; filename = ""; outStream = new MemoryStream(); document = new iTextSharp.text.Document(); copier = new PdfCopy(document, outStream); document.Open(); } catch (Exception ex) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); string methodName = st.GetFrame(0).GetMethod().Name; string innerMsg = ""; if (ex.InnerException != null) { innerMsg = ex.InnerException.Message; } Log(methodName, ex.Message, innerMsg); return(false); } return(true); }
private System.IO.MemoryStream extractPagesFromPerfectBindStream(System.IO.MemoryStream orig_stream, int start_page = 1, int end_page = 1) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var doc = new iTextSharp.text.Document(); var writer = new iTextSharp.text.pdf.PdfCopy(doc, dest_stream); doc.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (var i = start_page; i <= end_page; i++) { var page = writer.GetImportedPage(reader, i); writer.AddPage(page); } reader.Close(); doc.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
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(); } }
public static void ConvertImageToPdf(string srcFilename, string dstFilename) { iTextSharp.text.Rectangle pageSize = null; using (var srcImage = new Bitmap(srcFilename)) { pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height); } using (var ms = new MemoryStream()) { var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0); iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression(); document.Open(); var image = iTextSharp.text.Image.GetInstance(srcFilename); document.Add(image); document.Close(); File.WriteAllBytes(dstFilename, ms.ToArray()); } }
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(); }
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(); }
/// <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(); }
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 (); } }
// Background worker public void PDFBackgroundWorker_DoWork_TextPDF(object sender, DoWorkEventArgs e) { int i = 0; int ii = 1; exportFilePath = string.Empty; if (JobType == PDFJobType.TextPDF) { exportFilePath = directoryName + "\\" + FileNoExt + ".pdf"; while (System.IO.File.Exists(exportFilePath)) { exportFilePath = directoryName + "\\" + FileNoExt + "_" + ii + ".pdf"; ii++; } using (FileStream fs = new FileStream(exportFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.B4); // iTextSharp.text. Document doc = new Document(PageSize.A2); // doc.SetMargins(100, 200, 0, 0); //Document doc = new Document(PageSize.A5, 36, 72, 108, 180); //Document doc = new Document(PageSize.A3.Rotate(),400,0,0,0); //var doc = new Document(new iTextSharp.text.Rectangle(100f, 300f)); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs); iTextSharp.text.pdf.BaseFont bfTimes = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.TIMES_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, false); // doc.SetPageSize(PageSize.A1); // doc.SetMargins(76, 0, 0, 0); doc.SetMarginMirroring(false); iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.CYAN); if (PDFBackgroundWorker.CancellationPending) { e.Cancel = true; PDFBackgroundWorker.ReportProgress(i); return; } using (StreamReader read = new StreamReader(InputFilename)) { string text = read.ReadToEnd(); // AddDocMetaData(); doc.AddTitle(GameTitle); doc.AddSubject(""); doc.AddKeywords(GameTitle + ", " + FileNoExt + " : by Hypermint, "); doc.AddCreator("HLM-Chk"); doc.AddAuthor(GameTitle); doc.AddHeader(FileNoExt, GameTitle); doc.Open(); iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(); paragraph.Alignment = iTextSharp.text.Element.ALIGN_MIDDLE; paragraph.Add(text); doc.Add(paragraph); //Paragraph paragraph = new Paragraph(text); doc.Close(); } } } }
protected void createPDF(Stream output) { //Construct tempConstruct = myConn.getConstructByID(Convert.ToInt16(Request.QueryString["id"])); Construct tempConstruct = myConn.getConstructByID(2); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=construct_" + tempConstruct.id + ".pdf"); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 72, 72, 72, 72); PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream); document.Open(); //Page title and spacing iTextSharp.text.Chunk pageTitle = new iTextSharp.text.Chunk("Construct Record", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20)); document.Add(pageTitle); iTextSharp.text.Paragraph spacing = new iTextSharp.text.Paragraph(" "); document.Add(spacing); //Name iTextSharp.text.Paragraph tempParagraph = new iTextSharp.text.Paragraph(); iTextSharp.text.Chunk tempLabel = new iTextSharp.text.Chunk("Construct Name: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); iTextSharp.text.Chunk tempValue = new iTextSharp.text.Chunk(tempConstruct.name, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Insert tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Insert: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.insert, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Vector tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Vector: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.vector, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Species tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Species: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.species, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Antibiotic Resistance tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Antibiotic Resistance: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.antibioticResistance, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //5' Digest Site tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("5' Digest Site: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.digestSite5, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //3' Digest Site tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Working Dilution: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.digestSite3, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Notes tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Notes: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempConstruct.notes, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); document.Close(); }
protected void Exportchart(ArrayList chart) { string uid = Session["UserID"].ToString(); MemoryStream msReport = new MemoryStream(); try { document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 72, 72, 82, 72); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, msReport); document.AddAuthor("Test"); document.AddSubject("Export to PDF"); document.Open(); for (int i = 0; i < chart.Count; i++) { iTextSharp.text.Chunk c = new iTextSharp.text.Chunk("Export chart to PDF", iTextSharp.text.FontFactory.GetFont("VERDANA", 15)); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.Alignment = iTextSharp.text.Element.ALIGN_CENTER; iTextSharp.text.Image hImage = null; hImage = iTextSharp.text.Image.GetInstance(MapPath(chart[i].ToString())); float NewWidth = 500; float MaxHeight = 400; if (hImage.Width <= NewWidth) { NewWidth = hImage.Width; } float NewHeight = hImage.Height * NewWidth / hImage.Width; if (NewHeight > MaxHeight) { NewWidth = hImage.Width * MaxHeight / hImage.Height; NewHeight = MaxHeight; } float ratio = hImage.Width / hImage.Height; hImage.ScaleAbsolute(NewWidth, NewHeight); document.Add(p); document.Add(hImage); } // close it document.Close(); string filename = "Appraisal Overview for " + Session["Name"].ToString() + ".pdf"; Response.AddHeader("Content-type", "application/pdf"); Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); Response.OutputStream.Write(msReport.GetBuffer(), 0, msReport.GetBuffer().Length); } catch (System.Threading.ThreadAbortException ex) { throw new Exception("Error occured: " + ex); } }
/// <summary> /// Creates the PDF document. /// </summary> /// <param name="filename">The filename.</param> private void CreatePDFDocument(string filename) { try { this._document = new iTextSharp.text.Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(this._document, new FileStream(filename, FileMode.Create)); this._document.Open(); } catch(Exception) { throw; } }
protected void createPDF(Stream output) { //Vector tempVector = myConn.getVectorByID(Convert.ToInt16(Request.QueryString["id"])); Vector tempVector = myConn.getVectorByID(2); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=vector_" + tempVector.id + ".pdf"); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 72, 72, 72, 72); PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream); document.Open(); //Page title and spacing iTextSharp.text.Chunk pageTitle = new iTextSharp.text.Chunk("Vector Record", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20)); document.Add(pageTitle); iTextSharp.text.Paragraph spacing = new iTextSharp.text.Paragraph(" "); document.Add(spacing); //Name iTextSharp.text.Paragraph tempParagraph = new iTextSharp.text.Paragraph(); iTextSharp.text.Chunk tempLabel = new iTextSharp.text.Chunk("Vector Name: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); iTextSharp.text.Chunk tempValue = new iTextSharp.text.Chunk(tempVector.vectorName, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Multiple Cloning Site tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Multiple Cloning Site: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempVector.multipleCloningSite, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Antibiotic Resistance tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Antibiotic Resistance: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempVector.antibioticResistance, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Vector Size tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Vector Size: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempVector.vectorSize, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Promoter tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Promoter: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempVector.promoter, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Notes tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Notes: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempVector.notes, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); document.Close(); }
public static void CombineMultiplePDFs(string[] fileNames, string outFile) { try { iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return; } document.Open(); foreach (string fileName in fileNames) { if (System.IO.File.Exists(fileName)) { PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyDocumentFields(reader); } reader.Close(); } } writer.Close(); document.Close(); } catch { MessageBox.Show("Close the pdf file and try again."); } }
public static Byte[] GetCreatePdf() { var doc = new iTextSharp.text.Document(); var ms = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, ms); var random = new Random(); doc.Open(); for (var i = 0; i < 5; i++) { doc.Add(new iTextSharp.text.Paragraph(GetRandomString(random))); } doc.Close(); return ms.ToArray(); }
/// <summary> /// kein .pdf anhängen (macht er automatisch) /// </summary> /// <param name="name"></param> public void createPDF(string name) { this.getMindestbreite(); iTextSharp.text.Document doc = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(doc, System.IO.File.Create(name + ".pdf")); doc.Open(); PdfContentByte pCon = writer.DirectContent; pCon.SetLineWidth(0.3f); draw(new DrawContextDocument(pCon, iTextSharp.text.BaseColor.BLACK, new float[] { 10, 10 + 1000 }, new float[] { 10, 10 + getHeight(1000) }, 10, 10, 0)); //pCon.SetColorStroke(new iTextSharp.text.BaseColor(Color.Black)); //pCon.SetColorFill(new iTextSharp.text.BaseColor(Color.Black)); //pCon.Stroke(); doc.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(); }
// 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 System.Web.Mvc.FileResult ExportPdf(long DocumentID) { iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 50, 20, 70); MemoryStream output = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, output); long userId = Convert.ToInt64(HttpContext.User.Identity.Name); OpenBookSystemMVC.OBISReference.Document doc = null; OBSDataSource.GetDocument(DocumentID, out doc); AccountInfo ai = null; OBSDataSource.GetUserProfile(userId, out ai); if (doc == null || ai == null) { return null; } string returnContent = doc.SimplifiedContent; if (ai.Preferences.DocumentFontSize == 0) { returnContent = returnContent.ToUpper(); } pdfDoc.Open(); iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); if (ai.Preferences != null) { iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/verdana.ttf"), "Verdana"); iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/times.ttf"), "Times New Roman"); iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/calibri.ttf"), "Calibri"); iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/tahoma.ttf"), "Tahoma"); iTextSharp.text.Font font = iTextSharp.text.FontFactory.GetFont( ai.Preferences.DocumentFontName, ai.Preferences.DocumentFontSize > 0 ? ai.Preferences.DocumentFontSize : 18); ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.FACE, ai.Preferences.DocumentFontName); } else { ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.FACE, "Times New Roman"); } ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.ENCODING, BaseFont.IDENTITY_H); List<iTextSharp.text.IElement> htmlElements = HTMLWorker.ParseToList(new StringReader(returnContent), ST); FormatImgElements(htmlElements); foreach (var item in htmlElements) { pdfDoc.Add(item); } pdfDoc.Close(); var bytes = output.ToArray(); return File(bytes, "application/pdf", string.Format("{0}.pdf", doc.Title)); }
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(); } }
protected void createPDF(Stream output) { //PrimaryAntibody tempAntibody = myConn.getPrimaryAntibodyByID(Convert.ToInt16(Request.QueryString["id"])); PrimaryAntibody tempAntibody = myConn.getPrimaryAntibodyByID(int.Parse(txtid.Value)); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=primary_antibody_" + tempAntibody.id + ".pdf"); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 72, 72, 72, 72); PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream); document.Open(); //Page title and spacing iTextSharp.text.Chunk pageTitle = new iTextSharp.text.Chunk("Primary Antibody Record", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20)); document.Add(pageTitle); iTextSharp.text.Paragraph spacing = new iTextSharp.text.Paragraph(" "); document.Add(spacing); //Name iTextSharp.text.Paragraph tempParagraph = new iTextSharp.text.Paragraph(); iTextSharp.text.Chunk tempLabel = new iTextSharp.text.Chunk("Name: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); iTextSharp.text.Chunk tempValue = new iTextSharp.text.Chunk(tempAntibody.name, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Type tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Type: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.type, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Clone tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Clone: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.clone, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Host Species tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Host Species: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.hostSpecies, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Reactive Species tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Reactive Species: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.reactiveSpecies, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Concentration tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Concentration: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.concentration, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Working Dilution tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Working Dilution: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.workingDilution, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Applications tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Applications: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.applications, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Isotype tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Isotype: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.isotype, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Antigen tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Antigen: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.antigen, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Fluorophore tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Fluorophore: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.fluorophore, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); document.Close(); }
protected void lnkpdfdownload_Click(object sender, EventArgs e) { using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { //To Export all pages gvStudents.AllowPaging = false; this.RefreshGridView(); gvStudents.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 5f, 5f, 5f, 0f); iTextSharp.text.html.simpleparser.HTMLWorker htmlparser = new iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc); iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.pdf", String.Concat("StudentsDetails", DateTime.Now.Ticks))); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End(); } } }
/// <summary> /// a megadott file elérési úttal elkészíti a pdf dokumentumot /// </summary> /// <param name="financedAmount"></param> /// <param name="calcValues"></param> /// <param name="pdfFileWithPath"></param> /// <returns></returns> public void CreateLeasingDocument(string financedAmount, System.Collections.Specialized.StringCollection calcValues, string pdfFileWithPath) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 36, 36); //marginTop : 72 try { // writer letrehozas iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(pdfFileWithPath, System.IO.FileMode.Create)); // lablec iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new iTextSharp.text.Phrase(), true); footer.Border = iTextSharp.text.Rectangle.NO_BORDER; footer.Alignment = iTextSharp.text.HeaderFooter.ALIGN_CENTER; document.Footer = footer; // dokumentum megnyitas document.Open(); iTextSharp.text.Chapter chapter1 = new iTextSharp.text.Chapter(2); chapter1.NumberDepth = 0; //fejlec kep iTextSharp.text.Image imgHeader = GetHeaderImageFile(); imgHeader.Alignment = iTextSharp.text.Image.ALIGN_LEFT; imgHeader.Alt = "NE VEDD MEG, BÉRELD!"; iTextSharp.text.Table hTable = new iTextSharp.text.Table(1, 1); iTextSharp.text.Cell hCell = new iTextSharp.text.Cell(imgHeader); hTable.AutoFillEmptyCells = true; hTable.TableFitsPage = true; hTable.WidthPercentage = 100; hTable.AddCell(hCell); hTable.Alignment = iTextSharp.text.Table.ALIGN_LEFT; chapter1.Add(hTable); iTextSharp.text.Color defaultTextColor = new iTextSharp.text.Color(0, 0, 128); //uj sor, tavtarto a tabla es a fejleckep kozott chapter1.Add(new iTextSharp.text.Paragraph(" ")); iTextSharp.text.pdf.BaseFont default_ttf = iTextSharp.text.pdf.BaseFont.CreateFont(CompanyGroup.Helpers.ConfigSettingsParser.GetString("FontFile", "c:\\Windows\\Fonts\\calibri.ttf"), iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED); iTextSharp.text.Font titlefont = new iTextSharp.text.Font(default_ttf, 16, iTextSharp.text.Font.BOLDITALIC, defaultTextColor); iTextSharp.text.Font defaultFont = new iTextSharp.text.Font(default_ttf, 15, iTextSharp.text.Font.NORMAL, defaultTextColor); //cimsor iTextSharp.text.Paragraph pgTitle = new iTextSharp.text.Paragraph("Finanszírozási ajánlat", titlefont); chapter1.Add(pgTitle); //tablazat iTextSharp.text.Table table1 = new iTextSharp.text.Table(2, 1); table1.BorderColor = table1.DefaultCellBorderColor = defaultTextColor; table1.Padding = 2; table1.Spacing = 1; table1.AutoFillEmptyCells = true; table1.Alignment = iTextSharp.text.Table.ALIGN_LEFT; table1.WidthPercentage = 80.0f; table1.Widths = new float[] { 60, 20 }; iTextSharp.text.Paragraph tmpParagraph = new iTextSharp.text.Paragraph("A konfiguráció nettó vételára:", defaultFont); iTextSharp.text.Cell cell1 = new iTextSharp.text.Cell(tmpParagraph); cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell1.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table1.AddCell(cell1); tmpParagraph = new iTextSharp.text.Paragraph(financedAmount + " Ft", defaultFont); iTextSharp.text.Cell cell2 = new iTextSharp.text.Cell(tmpParagraph); cell2.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell2.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; table1.AddCell(cell2); chapter1.Add(table1); //5 oszlopos tabla iTextSharp.text.Table table2 = new iTextSharp.text.Table(5); table2.BorderColor = defaultTextColor; table2.Padding = 2; table2.Spacing = 1; table2.AutoFillEmptyCells = true; table2.Alignment = iTextSharp.text.Table.ALIGN_LEFT; table2.WidthPercentage = 100.0f; table2.Widths = new float[] { 20, 20, 20, 20, 20 }; //első sor tmpParagraph = new iTextSharp.text.Paragraph("Önerő", defaultFont); cell1 = new iTextSharp.text.Cell(tmpParagraph); cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell1.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell1.Header = true; cell1.Colspan = 4; cell1.BorderColor = defaultTextColor; table2.AddCell(cell1); tmpParagraph = new iTextSharp.text.Paragraph("0 Ft", defaultFont); cell2 = new iTextSharp.text.Cell(tmpParagraph); cell2.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell2.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell2.BorderColor = defaultTextColor; table2.AddCell(cell2); //második sor //table2.AddCell(""); tmpParagraph = new iTextSharp.text.Paragraph("Deviza: HUF", defaultFont); iTextSharp.text.Cell tmpCell = new iTextSharp.text.Cell(tmpParagraph); tmpCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; tmpCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; tmpCell.BorderColor = defaultTextColor; tmpCell.Rowspan = 2; table2.AddCell(tmpCell); tmpParagraph = new iTextSharp.text.Paragraph("Futamidő hónapokban", defaultFont); cell1 = new iTextSharp.text.Cell(tmpParagraph); cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell1.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell1.BorderColor = defaultTextColor; cell1.Colspan = 4; table2.AddCell(cell1); //harmadik sor tmpParagraph = new iTextSharp.text.Paragraph("24", defaultFont); cell2 = new iTextSharp.text.Cell(tmpParagraph); cell2.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell2.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell2.BorderColor = defaultTextColor; table2.AddCell(cell2); tmpParagraph = new iTextSharp.text.Paragraph("36", defaultFont); iTextSharp.text.Cell cell3 = new iTextSharp.text.Cell(tmpParagraph); cell3.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell3.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell3.BorderColor = defaultTextColor; table2.AddCell(cell3); tmpParagraph = new iTextSharp.text.Paragraph("48", defaultFont); iTextSharp.text.Cell cell4 = new iTextSharp.text.Cell(tmpParagraph); cell4.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell4.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell4.BorderColor = defaultTextColor; table2.AddCell(cell4); tmpParagraph = new iTextSharp.text.Paragraph("60", defaultFont); iTextSharp.text.Cell cell5 = new iTextSharp.text.Cell(tmpParagraph); cell5.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell5.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell5.BorderColor = defaultTextColor; table2.AddCell(cell5); //negyedik sor tmpParagraph = new iTextSharp.text.Paragraph("Tartós bérlet", defaultFont); cell1 = new iTextSharp.text.Cell(tmpParagraph); cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell1.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell1.BorderColor = defaultTextColor; table2.AddCell(cell1); tmpParagraph = new iTextSharp.text.Paragraph(GetItemByPositionFromStringCollection(0, calcValues), defaultFont); cell2 = new iTextSharp.text.Cell(tmpParagraph); cell2.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell2.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell2.BorderColor = defaultTextColor; table2.AddCell(cell2); tmpParagraph = new iTextSharp.text.Paragraph(GetItemByPositionFromStringCollection(1, calcValues), defaultFont); cell3 = new iTextSharp.text.Cell(tmpParagraph); cell3.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell3.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell3.BorderColor = defaultTextColor; table2.AddCell(cell3); tmpParagraph = new iTextSharp.text.Paragraph(GetItemByPositionFromStringCollection(2, calcValues), defaultFont); cell4 = new iTextSharp.text.Cell(tmpParagraph); cell4.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell4.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell4.BorderColor = defaultTextColor; table2.AddCell(cell4); tmpParagraph = new iTextSharp.text.Paragraph(GetItemByPositionFromStringCollection(3, calcValues), defaultFont); cell5 = new iTextSharp.text.Cell(tmpParagraph); cell5.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; cell5.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell5.BorderColor = defaultTextColor; table2.AddCell(cell5); //ötödik sor table2.AddCell(""); tmpParagraph = new iTextSharp.text.Paragraph("Nettó havidíjak", defaultFont); cell1 = new iTextSharp.text.Cell(tmpParagraph); cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell1.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell1.BorderColor = defaultTextColor; cell1.Colspan = 4; table2.AddCell(cell1); //hatodik sor //tmpParagraph = new iTextSharp.text.Paragraph( "A kalkulált díjak biztosítási díjat is tartalmaznak.", defaultFont ); //cell1 = new iTextSharp.text.Cell( tmpParagraph ); //cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; //cell1.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; //cell1.BorderColor = defaultTextColor; //cell1.Colspan = 5; //table2.AddCell(cell1); chapter1.Add(table2); chapter1.Add(new iTextSharp.text.Paragraph(" ")); //szoveg iTextSharp.text.Font smallFont = new iTextSharp.text.Font(default_ttf, 9, iTextSharp.text.Font.ITALIC, defaultTextColor); iTextSharp.text.Paragraph sText = new iTextSharp.text.Paragraph("HUF alapú finanszírozás, a havi díj az 1 havi Buborhoz kötött", smallFont); chapter1.Add(sText); //uj sor chapter1.Add(new iTextSharp.text.Paragraph(" ")); //szoveg iTextSharp.text.Font bold_10_Font = new iTextSharp.text.Font(default_ttf, 10, iTextSharp.text.Font.BOLD, defaultTextColor); sText = new iTextSharp.text.Paragraph("Ajánlatunkat ajánlati kötöttség nélkül tettük meg!", bold_10_Font); chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("Az ügylet megkötéséhez a refinanszírozó jóváhagyása szükséges.", bold_10_Font); chapter1.Add(sText); //uj sor chapter1.Add(new iTextSharp.text.Paragraph(" ")); ////szoveg //var bold_12_Font = new iTextSharp.text.Font( default_ttf, 12, iTextSharp.text.Font.BOLD, defaultTextColor ); //sText = new iTextSharp.text.Paragraph( "Szerződéskötési díj: 0 Ft", bold_12_Font ); //chapter1.Add(sText); ////uj sor //chapter1.Add(new iTextSharp.text.Paragraph(" ")); //szoveg sText = new iTextSharp.text.Paragraph("A tartós bérlet alapvető jellemzői", bold_10_Font); chapter1.Add(sText); //szoveg iTextSharp.text.Font normal_10_Font = new iTextSharp.text.Font(default_ttf, 10, iTextSharp.text.Font.NORMAL, defaultTextColor); sText = new iTextSharp.text.Paragraph("A bérleti díjakat ÁFA terheli, mely visszaigényelhető", normal_10_Font); sText.IndentationLeft = 50; chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("Az eszköz a bérbeadó könyveiben kerül aktiválásra", normal_10_Font); sText.IndentationLeft = 50; chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("A havi díj költségként elszámolható, csökkentve ezáltal az adóalapot", normal_10_Font); sText.IndentationLeft = 50; chapter1.Add(sText); //uj sor chapter1.Add(new iTextSharp.text.Paragraph(" ")); //szoveg sText = new iTextSharp.text.Paragraph("Ha bármilyen kérdése merülne fel a konstrukciót illetően, forduljon hozzánk bizalommal!", bold_10_Font); chapter1.Add(sText); //uj sor chapter1.Add(new iTextSharp.text.Paragraph(" ")); //szoveg sText = new iTextSharp.text.Paragraph("Kublik Ádám", bold_10_Font); chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("értékesítési vezető", normal_10_Font); chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("HRP Finance", bold_10_Font); chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("Tel.: +36 1 452 46 16", normal_10_Font); chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("mob.: +36 70 452 46 16", normal_10_Font); chapter1.Add(sText); //szoveg sText = new iTextSharp.text.Paragraph("mail: [email protected]", normal_10_Font); chapter1.Add(sText); document.Add(chapter1); } catch (iTextSharp.text.DocumentException documentException) { throw documentException; } catch (System.IO.IOException ioeException) { throw ioeException; } finally { // dokumentum bezarasa document.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(); }
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ę."); } }
public void PrintException(string exceptionmessage) { string errorfilepath = data["source_dir"] + @"\ERROR.pdf"; FileStream fs = new FileStream(errorfilepath, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document pdf1 = new iTextSharp.text.Document(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdf1, fs); pdf1.Open(); pdf1.Add(new iTextSharp.text.Paragraph(exceptionmessage)); pdf1.Close(); //string newFile = data["temp_directory"] + "\\" + System.Guid.NewGuid().ToString() + ".pdf"; System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;//.Hidden; startInfo.FileName = data["PDF_PRINT"]; startInfo.Arguments = " \"-$\" \"" + data["PDF_PRINT_KEY"] + "\" -paper 1 -scale " + data["PAPER_SCALE"] + " -xoffset " + data["PAPER_OFFSET_X"] + " -yoffset " + data["PAPER_OFFSET_Y"] + " -preproc -raster -chgbin " + data["DEFAULT_PRINTER_TRAY"] + " -printer \"" + data["DEFAULT_PRINTER"] + "\" \"" + errorfilepath + "\""; process.StartInfo = startInfo; process.Start(); process.WaitForExit(); process.Dispose(); System.Threading.Thread.Sleep(1000); //test /* string errorfilepath = @"C:\Users\Administrator.EYEDOC\Documents\Visual Studio 2013\Projects\FIX_HL7_BILLING\FIX_HL7_BILLING\ERROR.pdf"; FileStream fs = new FileStream(@"C:\Users\Administrator.EYEDOC\Documents\Visual Studio 2013\Projects\FIX_HL7_BILLING\FIX_HL7_BILLING\ERROR.pdf", FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document pdf1 = new iTextSharp.text.Document(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdf1, fs); pdf1.Open(); string timenow = DateTime.Now.ToLongTimeString(); pdf1.Add(new iTextSharp.text.Paragraph(timenow)); pdf1.Close(); */ /* //try ASPOSE////////////////////////////////////////////////////////////////////////////////this works. just need the license key. PdfViewer viewer = new PdfViewer(); viewer.BindPdf(errorfilepath);//Set attributes for printing viewer.AutoResize = true; //Print the file with adjusted size viewer.AutoRotate = true; //Print the file with adjusted rotation viewer.PrintPageDialog = false; //Do not produce the page number dialog when printing //Create objects for printer and page settings and PrintDocument System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings(); System.Drawing.Printing.PageSettings pgs = new System.Drawing.Printing.PageSettings(); System.Drawing.Printing.PrintDocument prtdoc = new System.Drawing.Printing.PrintDocument(); //Set printer name ps.PrinterName = prtdoc.PrinterSettings.PrinterName; //ps.PrinterName = "Canon Front iR3245"; //Print document using printer and page settings viewer.PrintDocumentWithSettings(pgs, ps); //Close the PDF file after priting viewer.Close(); ////////////////////////////////////////////////////////////////// */ //caution using this method bc we have lots of things using pdfprint already and recall we need extra instances of the program to avoid file corruption. /* // string newFile = data["temp_directory"] + "\\" + System.Guid.NewGuid().ToString() + ".pdf"; //not used System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;//.Hidden; startInfo.FileName = data["PDF_PRINT"]; startInfo.Arguments = " \"-$\" \"" + data["PDF_PRINT_KEY"] + "\" -paper 1 -scale " + data["PAPER_SCALE"] + " -xoffset " + data["PAPER_OFFSET_X"] + " -yoffset " + data["PAPER_OFFSET_Y"] + " -preproc -raster -chgbin " + data["DEFAULT_PRINTER_TRAY"] + " -printer \"" + data["DEFAULT_PRINTER"] + "\" \"" + errorfilepath + "\""; process.StartInfo = startInfo; //process.StartInfo.UseShellExecute = false;//hijack print console // process.StartInfo.RedirectStandardOutput = true;//hijack print console // var sb = new StringBuilder();//hijack print console //process.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);//hijack print console process.Start(); // process.BeginOutputReadLine(); //hijack output print process.WaitForExit(); process.Dispose(); //System.Threading.Thread.Sleep(1000); */ //end test }
// experimentell! public void createPdfFile(string filespec) { iTextSharp.text.Document doc = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(0, 0, box.Width, box.Height)); dynamic writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new System.IO.FileStream(filespec, System.IO.FileMode.Create)); dynamic bf = iTextSharp.text.pdf.BaseFont.CreateFont(); doc.Open(); iTextSharp.text.pdf.PdfContentByte over = writer.DirectContent; for (i = 0; i <= p_objects.Count - 1; i++) { RECT r = p_objects[i].GetOuterBounds; if (p_objects[i] is VTextbox) { VTextbox src = p_objects[i]; //ColumnText can contain paraphraphs as well as be abolsutely positioned iTextSharp.text.pdf.ColumnText Col = new iTextSharp.text.pdf.ColumnText(over); //Set the x,y,width,height Col.SetSimpleColumn(r.Left, box.Height - r.Top, r.Right, box.Height - r.Bottom); //Create our paragraph iTextSharp.text.Paragraph P = new iTextSharp.text.Paragraph(); //Create our base font, assumes you have arial installed in the normal location and that CP1252 works with it //Dim BF = BaseFont.CreateFont(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows), "Fonts\arial.ttf"), BaseFont.CP1252, False) //Add two chunks that will be placed side-by-side but with different font weights //P.Add(New iTextSharp.text.Chunk("BOLD TEXT: ", New iTextSharp.text.Font(bf, 10.0, iTextSharp.text.Font.BOLD))) string fontFilespec = Helper.GetFontFilespec(src.Font.FontFamily.Name); iTextSharp.text.Font fnt = default(iTextSharp.text.Font); if (!string.IsNullOrEmpty(fontFilespec)) { fnt = new iTextSharp.text.Font(iTextSharp.text.pdf.BaseFont.CreateFont(fontFilespec, iTextSharp.text.pdf.BaseFont.CP1252, false), src.Font.SizeInPoints, iTextSharp.text.Font.NORMAL); } else { fnt = new iTextSharp.text.Font(bf, src.Font.SizeInPoints, iTextSharp.text.Font.NORMAL); } P.Add(new iTextSharp.text.Chunk(src.Text, fnt)); //Add the paragraph to the ColumnText Col.AddText(P); //Call to stupid Go() method which actually writes the content to the stream. Col.Go(); // //Dim txtbox As New iTextSharp.text.pdf.PdfPCell() //Dim f = New iTextSharp.text.Font(bf) //f.SetColor(0, 0, 0) //over.SetFontAndSize(bf, 10) //over.BeginText() //over.ShowTextAligned(1, src.Text, r.Left, box.Height - r.Bottom, 0) //over.EndText() } else { dynamic img = iTextSharp.text.Image.GetInstance(p_objects[i].GetAsImage, System.Drawing.Imaging.ImageFormat.Png); img.SetAbsolutePosition(r.Left, box.Height - r.Bottom); img.SetDpi(72, 72); //doc.Add(img) over.AddImage(img); } } doc.Close(); }
private void createPDF(String tempfilename, String newPath, Random random) { //MessageBox.Show("PDF"); string newFileName = tempfilename + ".pdf"; newPath = System.IO.Path.Combine(newPath, newFileName); int sizeofwrite = random.Next(1, 10000); if (!System.IO.File.Exists(newPath)) { // step 1: creation of a document-object iTextSharp.text.Document myDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate()); try { // step 2: // Now create a writer that listens to this doucment and writes the document to desired Stream. iTextSharp.text.pdf.PdfWriter.GetInstance(myDocument, new FileStream(newPath, FileMode.Create)); // step 3: Open the document now using myDocument.Open(); for (int x = 0; x < sizeofwrite; x++) { Byte[] b = new Byte[1]; random.NextBytes(b); // step 4: Now add some contents to the document myDocument.Add(new iTextSharp.text.Paragraph(b[0].ToString())); } } catch (iTextSharp.text.DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } finally { // step 5: Remember to close the documnet myDocument.Close(); textBox4.AppendText("Created file: " + newPath.ToString() + System.Environment.NewLine + "SIZE: " + sizeofwrite.ToString() + "\r\n\r\n"); } } }
public static void Main(string[] args) { var options = new Options(); CommandLine.ICommandLineParser cmdParser = new CommandLine.CommandLineParser(new CommandLine.CommandLineParserSettings(System.Console.Error)); if (cmdParser.ParseArguments(args, options)) { string connectionString = string.Format("URI=file:{0}", options.Database); #if (NET) var connection = new System.Data.SQLite.SQLiteConnection(connectionString); #else var connection = new Mono.Data.Sqlite.SqliteConnection(connectionString); #endif connection.Open(); var command = connection.CreateCommand(); command.CommandText = "CREATE TABLE IF NOT EXISTS at (id INTEGER PRIMARY KEY NOT NULL,name VARCHAR,surname VARCHAR,year INTEGER,gender CHAR,time VARCHAR)"; command.ExecuteNonQuery(); var repo = new AthleteRepository(command); switch (options.Action) { case Action.Module: { // 10mm d=> 28pt // 15mm => 42pt //float marginLeft, float marginRight, float marginTop, float marginBottom var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 36, 36); iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream("./module.pdf", System.IO.FileMode.Create)); document.Open(); var builder = new ModuleBuilder(document, options.YearEdition, 10); for (int page = 0; page < 10; page++) { builder.AddPage(); } document.Close(); break; } case Action.Insert: { System.Console.WriteLine("Drop all results?[y/N]?"); string yes = System.Console.ReadLine(); if (yes == "y") { FileHelpers.FileHelperEngine<Athlete> engine = new FileHelpers.FileHelperEngine<Athlete>(); Athlete[] athletes = engine.ReadFile(options.Input); repo.DeleteAll(); foreach (var a in athletes) { System.Console.WriteLine(a.Name); repo.Insert(a); } } break; } case Action.CreateList: case Action.CreateResult: { string catFileName = GetCatFileName(options); string reportFileName = GetReportFileName(options); var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 36, 36); iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(reportFileName, System.IO.FileMode.Create)); document.Open(); IBuilder builder = null; if (options.Action == Action.CreateList) { builder = new ListBuilder(document); } else { builder = new PdfBuilder(document); } Category[] cats = GetCategories(catFileName); foreach (Category cat in cats) { if (log.IsDebugEnabled) log.Debug("parse" + cat.Id); builder.BeginReport(cat.Title, options.YearEdition); var athletes = repo.Query(string.Format (cat.Sql, options.YearEdition)); foreach (Athlete athlete in athletes) { builder.Add(athlete); } builder.EndReport(); } document.Close(); break; } case Action.Interactive: { Category[] cats = GetCategories(GetCatFileName(options)); var parser = new TimeParser(); foreach (Category cat in cats) { System.Console.WriteLine("========{0}=========", cat.Id); var athletes = repo.Query(string.Format (cat.Sql, options.YearEdition)); foreach (Athlete athlete in athletes) { System.Console.Write("{0:00} {1}\t{2}({3}):", athlete.Id, athlete.Surname, athlete.Name, athlete.Gender); string time = string.Empty; string fmt = string.Empty; do { time = System.Console.ReadLine(); fmt = parser.Parse(time); if (!string.IsNullOrEmpty(fmt) ) { System.Console.WriteLine(fmt); repo.UpdateTime(athlete.Id, fmt); } else { if (time != "s") { System.Console.WriteLine("invalid.."); } } } while (string.IsNullOrEmpty(fmt) && time != "s"); } } break; } } connection.Close(); } }