//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; }
public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate) { Bitmap image = bm; if (rotate != RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(rotate); } using (FileStream stream = new FileStream(filename, FileMode.Create)) { using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN)) { iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream); pdfDocument.Open(); MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms); img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN)); pdfDocument.Add(img); pdfDocument.Close(); writer.Close(); } } }
/* ----------------------------------------------------------------- */ /// /// FromImage /// /// <summary> /// Creates a new instance of the PdfReader class from the /// specified image. /// </summary> /// /// <param name="src">Path of the image.</param> /// <param name="io">I/O handler.</param> /// /// <returns>PdfReader object.</returns> /// /* ----------------------------------------------------------------- */ public static PdfReader FromImage(string src, IO io) { using (var ms = new System.IO.MemoryStream()) using (var ss = io.OpenRead(src)) using (var image = Image.FromStream(ss)) { 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 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 void Export(string filename) { var fileInfo = new FileInfo(filename); var directory = fileInfo.Directory.FullName; var imageFileInfo = $"{directory}\\{fileInfo.Name}-image.jpg"; Rectangle bounds = this.Bounds; using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); } bitmap.Save(imageFileInfo, System.Drawing.Imaging.ImageFormat.Jpeg); } iTextSharp.text.Rectangle pageSize = null; using (var srcImage = new Bitmap(imageFileInfo)) { 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(imageFileInfo); document.Add(image); document.Close(); File.WriteAllBytes(filename, ms.ToArray()); } }
public static void Pdf(string filepath, string printData) { //simple file write check //using (System.IO.StreamWriter file = //new System.IO.StreamWriter(pdfFilePath, true)) //{ // file.WriteLine("Fourth line"); //} var author = "Dummy author"; var stream = new FileStream(filepath, FileMode.Create); // step 1 var document = new iTextSharp.text.Document(); // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.AddAuthor(author); document.Open(); // step 4 document.Add(new iTextSharp.text.Paragraph(printData)); document.Close(); stream.Dispose(); }
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 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 System.IO.MemoryStream ExtractPdfPagesToStream(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); }
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 static void ConvertToPdfUsingiTextSharp(string source, string destination) { try { iTextSharp.text.Rectangle pageSize; using (var srcImage = new Bitmap(source)) { 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(source); document.Add(image); document.Close(); File.WriteAllBytes(destination, ms.ToArray()); } } catch (Exception ex) { FileLogger.SetLog(string.Format(ExceptionConstants.ConvertToPdf, source, ex.Message)); } }
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(); } } } }
/// <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 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> /// 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); }
/// <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 generarXMLTokens(LinkedList <Token> tokens) { string path = "archivo.xml"; File.WriteAllText(path, ""); iTextSharp.text.Document doc = new iTextSharp.text.Document(); iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream("reporte.pdf", FileMode.Create)); doc.Open(); iTextSharp.text.Paragraph titulo = new iTextSharp.text.Paragraph(); titulo.Font = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA_BOLD, 18f, iTextSharp.text.BaseColor.ORANGE); titulo.Add("REPORTE DE TOKENS"); doc.Add(titulo); doc.Add(new iTextSharp.text.Paragraph("\n")); doc.Add(new iTextSharp.text.Paragraph("\n")); doc.Add(new iTextSharp.text.Paragraph("")); iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(4); table.AddCell("Tokens"); table.AddCell("Lexema"); table.AddCell("Fila"); table.AddCell("Columa"); if (File.Exists(path)) { using (StreamWriter file = File.AppendText(path)) { file.WriteLine("<ListaTokens>"); foreach (Token item in tokens) { table.AddCell(item.getToken()); table.AddCell(item.getValor()); table.AddCell(item.getFila().ToString()); table.AddCell(item.getColumna().ToString()); file.WriteLine( " <Token>\n" + " <Nombre>" + item.getToken() + "</Nombre>\n" + " <Valor>" + item.getValor() + "</Valor>\n" + " <Fila>" + item.getFila() + "</Fila>\n" + " <Columna>" + item.getColumna() + "</Columna>\n" + " </Token>\n"); } file.WriteLine("</ListaTokens>"); Console.WriteLine("si se modifico"); file.Close(); } doc.Add(table); doc.Close(); } /*Process p = new Process(); * p.StartInfo.FileName = path; * p.Start();*/ }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ internal bool CreatePDF(string PDFPath, ProgressBar PBar) { try { if (Tabs.Count > 0) { PBar.Invoke(new Action(() => { PBar.Maximum = Tabs.Count; PBar.Value = 0; PBar.Visible = true; PBar.Style = ProgressBarStyle.Marquee; })); if (File.Exists(PDFPath)) { File.Delete(PDFPath); } var CurDocument = new iTextSharp.text.Document(); var CurPdfWriter = PdfWriter.GetInstance(CurDocument, new FileStream(PDFPath, FileMode.Create, FileAccess.Write, FileShare.None)); CurPdfWriter.SetFullCompression(); Tabs = Tabs.OrderBy(o => o.Index).ToList(); for (int i = 0; i < Tabs.Count; i++) { var CurImage = Tabs[i].ScannedImage; var CurRectangle = new iTextSharp.text.Rectangle(CurImage.Width, CurImage.Height); CurDocument.SetPageSize(CurRectangle); CurDocument.SetMargins(0, 0, 0, 0); if (i == 0) { CurDocument.Open(); } if (i < (Tabs.Count - 1)) { CurDocument.NewPage(); } CurDocument.Add(iTextSharp.text.Image.GetInstance(CurImage, (iTextSharp.text.BaseColor)null)); PBar.Invoke(new Action(() => { PBar.Style = ProgressBarStyle.Continuous; PBar.Value++; })); } CurDocument.Close(); } else { MessageBox.Show("Keine Scanns vorhanden"); } GC.Collect(); return(true); } catch (Exception ex) { Program.MeldeFehler(ex.Message + "\n" + ex.StackTrace); Environment.Exit(1); return(false); } }
public void printOrder(List <Product> productsCart) { var file = Path.GetTempFileName(); string filepath = Path.GetTempPath(); string strFilename = MainUtils.getCurrentTime("h_mm_ss") + ".pdf"; using (MemoryStream ms = new MemoryStream()) { iTextSharp.text.Document document = new iTextSharp.text.Document(getPageSize(), 20, 20, 15, 15); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Path.Combine(filepath, strFilename), FileMode.Create)); document.AddTitle("Document Title"); document.Open(); iTextSharp.text.pdf.BaseFont Vn_Helvetica = iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", "Identity-H", iTextSharp.text.pdf.BaseFont.EMBEDDED); iTextSharp.text.Font titleFont = new iTextSharp.text.Font(Vn_Helvetica, 18, iTextSharp.text.Font.BOLD); iTextSharp.text.Font subTitleFont = new iTextSharp.text.Font(Vn_Helvetica, 14, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font boldTableFont = new iTextSharp.text.Font(Vn_Helvetica, 12, iTextSharp.text.Font.BOLD); iTextSharp.text.Font endingMessageFont = new iTextSharp.text.Font(Vn_Helvetica, 10, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font bodyFont = new iTextSharp.text.Font(Vn_Helvetica, 12, iTextSharp.text.Font.NORMAL); document.Add(new iTextSharp.text.Paragraph(Properties.Settings.Default.ShopName, titleFont)); var orderInfoTable = new PdfPTable(2); orderInfoTable.HorizontalAlignment = 0; orderInfoTable.SpacingBefore = 10; orderInfoTable.SpacingAfter = 10; orderInfoTable.DefaultCell.Border = 0; orderInfoTable.SetWidths(new int[] { 70, 150 }); //Id of Order orderInfoTable.AddCell(new iTextSharp.text.Phrase("Mã đơn hàng: ", boldTableFont)); orderInfoTable.AddCell(""); double totalPrice = 0; //Products for (int i = 0; i < productsCart.Count; i++) { int c = i + 1; orderInfoTable.AddCell(new iTextSharp.text.Phrase("Sản phẩm " + c + ": ", boldTableFont)); orderInfoTable.AddCell(new iTextSharp.text.Phrase(productsCart[i].getName(), bodyFont)); orderInfoTable.AddCell(new iTextSharp.text.Phrase("Mã sản phẩm " + c + ": ", boldTableFont)); orderInfoTable.AddCell(productsCart[i].getpID()); orderInfoTable.AddCell(new iTextSharp.text.Phrase("Số lượng " + c + ": ", boldTableFont)); orderInfoTable.AddCell(productsCart[i].getQuantity().ToString()); totalPrice += double.Parse(productsCart[i].getPrice()); } //Total price orderInfoTable.AddCell(new iTextSharp.text.Phrase("Tổng giá:", boldTableFont)); orderInfoTable.AddCell(Convert.ToDecimal(totalPrice).ToString("###,###,###.00") + " dong"); document.Add(orderInfoTable); document.Close(); } System.Diagnostics.Process.Start(filepath + strFilename); }
private byte[] Crop(byte[] pdfbytes, float llx, float lly, float urx, float ury) { byte[] rslt = null; // Allows PdfReader to read a pdf document without the owner's password iTextSharp.text.pdf.PdfReader.unethicalreading = true; // Reads the PDF document using (iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(pdfbytes)) { // Set which part of the source document will be copied. // PdfRectangel(bottom-left-x, bottom-left-y, upper-right-x, upper-right-y) iTextSharp.text.pdf.PdfRectangle rect = new iTextSharp.text.pdf.PdfRectangle(llx, lly, urx, ury); using (MemoryStream ms = new MemoryStream()) { // Create a new document //using (iTextSharp.text.Document doc = // new iTextSharp.text.Document(new iTextSharp.text.Rectangle(288f,432f))) using (iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4)) { // Make a copy of the document iTextSharp.text.pdf.PdfSmartCopy smartCopy = new iTextSharp.text.pdf.PdfSmartCopy(doc, ms) { PdfVersion = iTextSharp.text.pdf.PdfWriter.VERSION_1_7 }; smartCopy.CloseStream = false; // Open the newly created document doc.Open(); // Loop through all pages of the source document for (int i = 1; i <= pdfReader.NumberOfPages; i++) { doc.NewPage();// net necessary line // Get a page var page = pdfReader.GetPageN(i); // Apply the rectangle filter we created page.Put(iTextSharp.text.pdf.PdfName.CROPBOX, rect); page.Put(iTextSharp.text.pdf.PdfName.MEDIABOX, rect); // Copy the content and insert into the new document var copiedPage = smartCopy.GetImportedPage(pdfReader, i); smartCopy.AddPage(copiedPage); if (i.Equals(pdfReader.NumberOfPages)) { doc.NewPage(); smartCopy.AddPage(copiedPage); } } smartCopy.FreeReader(pdfReader); smartCopy.Close(); ms.Position = 0; rslt = ms.GetBuffer(); // Close the output document doc.Close(); } } return(rslt); } }
//image to pdf method public void Convert(string dir) { System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dir); System.IO.FileInfo[] pngfiles = di.GetFiles("*.png", System.IO.SearchOption.AllDirectories); System.IO.FileInfo[] jpgfiles = di.GetFiles("*.jpg", System.IO.SearchOption.AllDirectories); Console.WriteLine(pngfiles.Length); Console.WriteLine(jpgfiles.Length); string[] paths = new string[pngfiles.Length + jpgfiles.Length]; Console.WriteLine(paths.Length); var i = -1; foreach (var p in pngfiles) { i++; paths[i] = dir + "/" + p.ToString(); } foreach (var p in jpgfiles) { i++; paths[i] = dir + "/" + p.ToString(); } iTextSharp.text.Rectangle pageSize = null; using (var srcImage = new Bitmap(paths[0].ToString())) { 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(); //progress.Maximum = paths.Length; //progress.Value = 0; var prg = 0; foreach (var ii in paths) { label.Content = ii; var image = iTextSharp.text.Image.GetInstance(ii.ToString()); document.SetPageSize(new iTextSharp.text.Rectangle(0, 0, image.Width, image.Height)); document.Add(image); //progress.Value = prg; } document.Close(); File.WriteAllBytes(dir + ".pdf", ms.ToArray()); label.Content = "Conversion complete !"; } }
private void Imprimir_Click(object sender, EventArgs e) { if (dgvDados.RowCount == 0) { MessageBox.Show("Realize a pesquisa previamente"); } else { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { try { using (var fileStream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { var document = new iTextSharp.text.Document(); var pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fileStream); document.Open(); var paragraph = new iTextSharp.text.Paragraph("RELATÓRIO DE EMPRÉSTIMOS"); paragraph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; document.Add(paragraph); paragraph = new iTextSharp.text.Paragraph("DE: " + dtpInicio.Text + " ATÉ: " + dtpFim.Text); paragraph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; document.Add(paragraph); paragraph = new iTextSharp.text.Paragraph("\n"); document.Add(paragraph); for (int i = 0; i < dgvDados.RowCount; i++) { DateTime data = DateTime.Parse(dgvDados.Rows[i].Cells[6].Value.ToString()); paragraph = new iTextSharp.text.Paragraph(dgvDados.Rows[i].Cells[2].Value.ToString() + " " + dgvDados.Rows[i].Cells[3].Value.ToString() + " " + dgvDados.Rows[i].Cells[4].Value.ToString() + " " + dgvDados.Rows[i].Cells[5].Value.ToString() + " " + data.ToString("d")); paragraph.Alignment = iTextSharp.text.Element.ALIGN_JUSTIFIED; document.Add(paragraph); } document.Close(); System.Diagnostics.Process.Start(saveFileDialog1.FileName); } } catch (Exception ex) { MessageBox.Show(ex.Message, "ATENÇÃO"); } } } }
public void ExportPdfs_Click(object sender, EventArgs e) { RockContext rockContext = new RockContext(); rockContext.Database.CommandTimeout = 180; var files = GetBinaryFiles().Select(d => d.BinaryFile); PdfImportedPage importedPage; var outputStream = new MemoryStream(); Document sourceDocument = new Document(); PdfCopy pdfCopyProvider = new PdfCopy(sourceDocument, outputStream); //output file Open sourceDocument.Open(); Regex regex = new Regex(@"/Type\s*/Page[^s]"); foreach (var file in files) { if (file.MimeType == "application/pdf") { using (StreamReader sr = new StreamReader(file.ContentStream)) { MatchCollection matches = regex.Matches(sr.ReadToEnd()); int pages = matches.Count; PdfReader reader = new PdfReader(file.ContentStream); //Add pages in new file for (int i = 1; i <= pages; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } reader.Close(); } } } // Finish up the output sourceDocument.Close(); this.Page.EnableViewState = false; this.Page.Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=GivingStatementExport.pdf"); this.Page.Response.Charset = string.Empty; this.Page.Response.BinaryWrite(outputStream.ToArray()); this.Page.Response.Flush(); this.Page.Response.End(); }
private void SavePdf(string inputPath, string pathSaveFile) { // Create a new PDF document var doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); var fs = new FileStream(pathSaveFile, FileMode.Create); var wPdf = PdfWriter.GetInstance(doc, fs); doc.Open(); if (File.Exists(inputPath)) { //se arquivo unico var img = iTextSharp.text.Image.GetInstance(inputPath); doc.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height)); doc.NewPage(); img.SetAbsolutePosition(0, 0); wPdf.DirectContent.AddImage(img); } else { var imageFiles = Directory.GetFiles(inputPath, "*.*"); //.Where(f => fileExtensions.Contains(Path.GetExtension(f).ToLower())); //Array.Sort(imageFiles.ToArray(), new AlphanumComparatorFast()); //importing the images in the pdf foreach (string imageFile in imageFiles) { //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 img = iTextSharp.text.Image.GetInstance(imageFile); doc.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height)); doc.NewPage(); img.SetAbsolutePosition(0, 0); wPdf.DirectContent.AddImage(img); //} } } //save file doc.Close(); doc.Dispose(); fs.Close(); fs.Dispose(); wPdf.Close(); wPdf.Dispose(); }
private System.IO.MemoryStream imposeTypesetPerfectBindCover(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var docB4 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(1031.76f, 728.64f)); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB4, dest_stream); docB4.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); iTextSharp.text.pdf.PdfContentByte contentbyte; docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tCover = writer.GetImportedPage(reader, 1); contentbyte = writer.DirectContent; // default values: in PB briefs, y_coordinate will not vary float x_coordinate = 575.5f, y_coordinate = -76.5f; switch (LengthOfCover) { default: case 48: // GOOD: TESTED 11/16/15 y_coordinate = -88.5f; break; case 49: // STILL AN ESTIMATE y_coordinate = -82.5f; break; case 50: // GOOD: TESTED 11/16/15 y_coordinate = -76.5f; break; case 51: // GOOD: TESTED 11/16/15 y_coordinate = -70.5f; break; } contentbyte.AddTemplate(tCover, x_coordinate, y_coordinate); docB4.Close(); reader.Close(); writer.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
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 FileStreamResult PrintFormats(int idFormat, string RecordId) { if (!_tokenManager.GenerateToken()) { return(null); } _IGeneratePDFApiConsumer.SetAuthHeader(_tokenManager.Token); _ISpartan_FormatRelatedApiConsumer.SetAuthHeader(_tokenManager.Token); MemoryStream ms = new MemoryStream(); //Buscar los Formatos Relacionados var relacionados = _ISpartan_FormatRelatedApiConsumer.ListaSelAll(0, 5000, "Spartan_Format_Related.FormatId = " + idFormat, "").Resource.Spartan_Format_Relateds.OrderBy(r => r.Order).ToList(); if (relacionados.Count > 0) { var outputDocument = new iTextSharp.text.Document(); var writer = new PdfCopy(outputDocument, ms); outputDocument.Open(); foreach (var spartan_Format_Related in relacionados) { var bytePdf = _IGeneratePDFApiConsumer.GeneratePDF(Convert.ToInt32(spartan_Format_Related.FormatId_Related), RecordId).Resource; var reader = new PdfReader(bytePdf); for (var j = 1; j <= reader.NumberOfPages; j++) { writer.AddPage(writer.GetImportedPage(reader, j)); } writer.FreeReader(reader); reader.Close(); } writer.Close(); outputDocument.Close(); var allPagesContent = ms.GetBuffer(); ms.Flush(); } else { var bytePdf = _IGeneratePDFApiConsumer.GeneratePDF(idFormat, RecordId); ms.Write(bytePdf.Resource, 0, bytePdf.Resource.Length); } Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Formatos.pdf"); Response.Buffer = true; Response.Clear(); Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); Response.OutputStream.Flush(); Response.End(); return(new FileStreamResult(Response.OutputStream, "application/pdf")); }
private static void MergePDF(List <string> FileName, int ActiveId) { try { //string[] fileArray = new string[2]; //fileArray[0] = File1; //fileArray[1] = File2; PdfReader reader = null; // PdfReader.unethicalreading = true; iTextSharp.text.Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage; // string outputPdfPath = @"D:\SyncData\DeltaMDocuments\SymplifiedSuits\" + ActiveId.ToString() + ".pdf"; string outputPdfPath = @"C:\DeltaM\CRM\ClientsDocuments\SymplifiedSuits\" + ActiveId.ToString() + ".pdf"; sourceDocument = new iTextSharp.text.Document(); pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); //output file Open sourceDocument.Open(); //files list wise Loop for (int f = 0; f < FileName.Count; f++) { int pages = TotalPageCount(FileName[f]); if (pages > 0) { reader = new PdfReader(FileName[f]); if (pages < 2) { PdfReader.unethicalreading = true; } //Add pages in new file for (int i = 1; i <= pages; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } reader.Close(); } } //save the output file sourceDocument.Close(); } catch (Exception ex) { } }
/// <summary> /// Converts html to pdf file stream and retunrs bytes. /// </summary> /// <param name="strHtml">Html content to include in pdf.</param> /// <returns>Bytes to generate pdf file.</returns> public static byte[] ConvertHtmlToPdf(string strHtml) { iTextSharp.text.Document objDocument = new iTextSharp.text.Document(); try { MemoryStream objMemoryStream = new MemoryStream(); iTextSharp.text.pdf.PdfWriter objPdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance ( objDocument, objMemoryStream ); objDocument.Open(); iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml ( objPdfWriter, objDocument, new StringReader(strHtml) ); objDocument.Close(); return(objMemoryStream.ToArray()); } catch { } finally { if (objDocument != null) { objDocument.Close(); } objDocument = null; } return(null); }
static private string WriteCompatiblePdf(string sFilename) { // string s = System.IO.Path.GetTempPath(); string sNewPdf = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf"; sNewPdfs.Add(sNewPdf); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sFilename); // we retrieve the total number of pages int n = reader.NumberOfPages; // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(sNewPdf, FileMode.Create)); //write pdf that pdfsharp can understand writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4); // step 3: we open the document document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; iTextSharp.text.pdf.PdfImportedPage page; int rotation; int i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } // step 5: we close the document document.Close(); return(sNewPdf); }
/// <summary> /// Converts html to pdf file and retunrs pdf file path. /// </summary> /// <param name="strHtml">Html content to include in pdf.</param> /// <param name="strRootPath">Folder path to store generated pdf.</param> /// <returns>Path to the generated pdf file.</returns> public static string ConvertHtmlToPdf(string strHtml, string strRootPath, string strFileName) { iTextSharp.text.Document objDocument = new iTextSharp.text.Document(); string strFilePath = Path.Combine(strRootPath, string.Format("{0} {1}.pdf", strFileName, DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss-tt"))); try { iTextSharp.text.pdf.PdfWriter objPdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance ( objDocument, new FileStream(strFilePath, FileMode.Create) ); objDocument.Open(); iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml ( objPdfWriter, objDocument, new StringReader(strHtml) ); objDocument.Close(); } catch { } finally { if (objDocument != null) { objDocument.Close(); } objDocument = null; } return(strFilePath); }
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(); }
/// <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 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(); } }
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); } }
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(); }
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)); }
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 OnButtonPDFClicked(object sender, EventArgs e) { FileChooserDialog fc= new FileChooserDialog("Укажите файл для сохранения документа", this, FileChooserAction.Save, "Отмена",ResponseType.Cancel, "Сохранить",ResponseType.Accept); fc.CurrentName = DocInfo.TypeName + " " + entryNumber.Text + ".pdf"; fc.Show(); if(fc.Run() == (int) ResponseType.Accept) { fc.Hide(); iTextSharp.text.Document document = new iTextSharp.text.Document(); using (var stream = new FileStream(fc.Filename, FileMode.Create, FileAccess.Write, FileShare.None)) { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); document.Open(); foreach(DocumentImage img in Images) { if(img.Image.Width > img.Image.Height) document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); else document.SetPageSize(iTextSharp.text.PageSize.A4); document.NewPage(); var image = iTextSharp.text.Image.GetInstance(img.file); image.SetAbsolutePosition(0,0); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); } } fc.Destroy(); }
void SavePDF() { iTextSharp.text.Document document = new iTextSharp.text.Document(); using (var stream = new MemoryStream ()) { var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); foreach(Pixbuf pix in vimageslist1.Images) { if(pix.Width > pix.Height) document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); else document.SetPageSize(iTextSharp.text.PageSize.A4); document.NewPage(); var image = iTextSharp.text.Image.GetInstance(pix.SaveToBuffer ("jpeg")); image.SetAbsolutePosition(0,0); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); stream.Position = 0; File = stream.ToArray (); } }
/// <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(); } }
// 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(); } } } }
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(); } }
// 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(); }
// 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(); } } } }
/// <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(); }
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(); }
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."); } }
/// <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(); }
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(); }
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 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(); } }
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 }
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(); } } }
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"); } } }
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ę."); } }
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(); }