//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 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; }
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(); } }
static void Main(string[] args) { iTextSharp.text.Document ManagementReportDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 15f, 15f, 75f, 75f); FileStream file = new FileStream("E://" + DateTime.Now.ToString("dd-MMMM-yy") + ".pdf", System.IO.FileMode.OpenOrCreate); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(ManagementReportDoc, file); // PdfWriter.GetInstance(ManagementReportDoc, file); ManagementReportDoc.Open(); // step 4 将一个元素添加到文档中 ManagementReportDoc.Add(new iTextSharp.text.Paragraph("Hello World!")); // step 5 关闭文档 ManagementReportDoc.Close(); Console.ReadLine(); }
public ActionResult MerchantBillingStatementPdf() { if (Request.ContentLength == 0) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Nothing was submitted"); } Request.InputStream.Position = 0; using (var reader = new StreamReader(Request.InputStream)) { try { var content = reader.ReadToEnd(); var model = JsonConvert.DeserializeObject<MerchantBillingStatementContract>(content); if (model != null && !string.IsNullOrWhiteSpace(model.BusinessName)) { ViewData.Model = model; using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindView(ControllerContext, "MerchantBillingStatement", null); var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); using (var input = new MemoryStream(Encoding.UTF8.GetBytes(sw.GetStringBuilder().ToString()))) { var output = new MemoryStream(); var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 50, 50, 50, 50); var writer = PdfWriter.GetInstance(document, output); writer.CloseStream = false; document.Open(); var xmlWorker = XMLWorkerHelper.GetInstance(); xmlWorker.ParseXHtml(writer, document, input, Encoding.UTF8); document.Close(); output.Position = 0; return new FileStreamResult(output, "application/pdf"); } } } } catch (Exception ex) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest, ex.Message); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Content is missing"); }
public void Save(string fileName, Func <List <IElementRoot>, List <IElementRoot> > formatFunc = null) { if (formatFunc != null) { formatFunc.Invoke(Paragraphs); } string defaultFontPath = FontUtils.GetFontPath(ReportFactory.FontList, ReportFactory.FontStyle); iTextSharp.text.FontFactory.Register(defaultFontPath); using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)) { PageSize currentPageSize = PageSize ?? ReportFactory.PageSize; PageOrientation pageOrientation = PageOrientation ?? ReportFactory.PageOrientation; iTextSharp.text.Rectangle pageSize = currentPageSize.ToRectangle(pageOrientation); using (var document = new iTextSharp.text.Document(pageSize)) { float marginTop = MarginLeft ?? ReportFactory.MarginLeft; float marginRight = MarginLeft ?? ReportFactory.MarginRight; float marginBottom = MarginLeft ?? ReportFactory.MarginBottom; float marginLeft = MarginLeft ?? ReportFactory.MarginLeft; document.SetMargins(marginLeft, marginRight, marginTop, marginBottom); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fileStream); document.Open(); foreach (var para in Paragraphs) { if (para is Table) { iTextSharp.text.pdf.PdfPTable tableSource = para as Table; document.Add(tableSource); } else if (para is Paragraph) { iTextSharp.text.Paragraph paragraph = para as Paragraph; document.Add(paragraph); } } document.Close(); } fileStream.Close(); } }
public void MergeDocument() { List <string> files = new List <string>(); DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\PDFGenerator"); foreach (var file in directoryInfo.GetFiles()) { files.Add(file.FullName); } PdfReader reader = null; iTextSharp.text.Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage; string outputPdfPath = @"C:\PDFGenerator\newFile.pdf"; sourceDocument = new iTextSharp.text.Document(); pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); sourceDocument.Open(); try { foreach (string file in files) { int pages = get_pageCcount(file); reader = new PdfReader(file); for (int i = 1; i <= pages; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } reader.Close(); } sourceDocument.Close(); } catch (Exception ex) { throw ex; } }
private void btDataBase_Click(object sender, EventArgs e) { using (var context = new HramulEntities()) { var angajati = (from a in context.Salariis select a).ToList(); DataGridView grid = new DataGridView(); grid.DataSource = angajati; Controls.Add(grid); Controls.Remove(grid); PdfPTable pdfTable = new PdfPTable(grid.ColumnCount); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 60; pdfTable.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 1; foreach (DataGridViewColumn column in grid.Columns) { PdfPCell cell = new PdfPCell(new iTextSharp.text.Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240); pdfTable.AddCell(cell); } foreach (DataGridViewRow row in grid.Rows) { foreach (DataGridViewCell cell in row.Cells) { pdfTable.AddCell(cell.Value.ToString()); } } string file = "DataBaseExport.pdf"; using (FileStream stream = new FileStream(file, FileMode.Create)) { iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A2, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); } } MessageBox.Show("Baza de date a fost exportata"); }
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"); }
public void CrearPdf(string filePath, List <T> lista) { try { iTextSharp.text.Document doc = new iTextSharp.text.Document(); PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); doc.Open(); foreach (object objeto in lista) { doc.Add(new iTextSharp.text.Paragraph(objeto.ToString())); doc.Add(new iTextSharp.text.Paragraph("-----------------------------------------------------------------------------------")); } doc.Close(); } catch (Exception e) { throw e; } }
public bool escribirArchivo(string path, Documento data) { try { iTextSharp.text.Document doc = new iTextSharp.text.Document(); PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create)); doc.Open(); doc.Add(new iTextSharp.text.Paragraph(Program.Controlador.VistaEditor.RichTextBox1.Text)); doc.Close(); return(true); } catch { return(false); } }
public override byte[] GetDocument() { MemoryStream stream = new MemoryStream(); var doc = new iTextSharp.text.Document(); var writer = PdfWriter.GetInstance(doc, stream); doc.Open(); ProcessDocument(); WriteToDoc(new PdfDesignerFactory(doc, writer)); doc.Close(); var byteDoc = stream.ToArray(); stream.Dispose(); return(byteDoc); }
/// <summary> /// Copy a series of pages (in order) from our file into a destination file. /// </summary> /// <param name="destFile"></param> /// <param name="pageNumbers"></param> public void CopyPages(FileInfo destFile, IEnumerable <int> pageNumbers) { using (var binaryWriter = destFile.Create()) { var doc = new iTextSharp.text.Document(); var pdfWriter = new PdfCopy(doc, binaryWriter); doc.Open(); foreach (var pNumber in pageNumbers) { var page = pdfWriter.GetImportedPage(_reader, pNumber); pdfWriter.AddPage(page); } doc.Close(); } }
/// <summary> /// from http://forum.pdfsharp.net/viewtopic.php?p=2069 /// uses itextsharp to convert any pdf to 1.4 compatible pdf /// </summary> static private string WritePdf1pt4Version(string inputPath) { var tempFileName = Path.GetTempFileName(); File.Delete(tempFileName); string outputPath = tempFileName + ".pdf"; iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(inputPath); // we retrieve the total number of pages int n = reader.NumberOfPages; // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); //write pdf that pdfsharp can understand writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4); // step 3: we open the document document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; iTextSharp.text.pdf.PdfImportedPage page; int rotation; int i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } // step 5: we close the document document.Close(); return(outputPath); }
/// <summary> /// Splits the PDF file /// </summary> /// <param name="filepath">The file to split</param> private void Split(string filepath) { this.statut.Text = "Début de la division"; this.statut.Refresh(); this.document.Text = Path.GetFileName(filepath); this.document.Refresh(); PdfReader reader = null; int currentPage = 1; int pageCount = 0; string dirPath = Path.GetDirectoryName(filepath); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); reader = new iTextSharp.text.pdf.PdfReader(filepath); reader.RemoveUnusedObjects(); pageCount = reader.NumberOfPages; string ext = System.IO.Path.GetExtension(filepath); for (int i = 1; i <= pageCount; i++) { this.statut.Text = "En cours de division " + i + " / " + pageCount; this.statut.Refresh(); iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath); string outfile = filepath.Replace(System.IO.Path.GetFileName(filepath), (System.IO.Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString()) + ext); outfile = outfile.Substring(0, dirPath.Length).Insert(dirPath.Length, string.Empty) + "\\" + Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString() + ext; reader1.RemoveUnusedObjects(); iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage)); iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.OpenOrCreate)); doc.Open(); for (int j = 1; j <= 1; j++) { iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage); pdfCpy.AddPage(page); currentPage += 1; } this.progressBar1.PerformStep(); this.progressPages = this.progressPages + 1; this.label1.Text = this.progressPages + " / " + this.nbpages; this.label1.Refresh(); this.statut.Text = "Fin de la division " + i + " / " + pageCount; this.statut.Refresh(); doc.Close(); pdfCpy.Close(); reader1.Close(); reader.Close(); } }
public static void createPdfFromImage(string imageFile, string pdfFile) { using (var ms = new MemoryStream()) { var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0); PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create)); iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression(); document.Open(); FileStream fs = new FileStream(imageFile, FileMode.Open); var image = iTextSharp.text.Image.GetInstance(fs); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); document.Close(); //open pdf file Process.Start("explorer.exe", pdfFile); } }
public override void Export(string f, DataTable dt) { if (File.Exists(f)) { File.Delete(f); } using (FileStream fs = File.OpenWrite(f)) { iTextSharp.text.Document document = new iTextSharp.text.Document(); var writer = PdfWriter.GetInstance(document, fs); PageEventHelper pageEventHelper = new PageEventHelper(); writer.PageEvent = pageEventHelper; document.Open(); ExportReport(document, dt); document.Close(); } }
public static void Convert(List <Tiff.PageInfo> il, string dstPath) { using (var file_stream = new FileStream(dstPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (var document = new iTextSharp.text.Document()) using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, file_stream)) { document.SetMargins(0, 0, 0, 0); document.Open(); foreach (Tiff.PageInfo info in il) { try { bool needRotate = info.Image.Width > info.Image.Height; if (needRotate) { info.Image.RotateFlip(RotateFlipType.Rotate90FlipNone); } Image gif = Image.GetInstance(info.Image, ImageFormat .Png); gif.ScaleAbsolute((float)(info.Image.Width * (72.0 / info.Image.HorizontalResolution)), (float)(info.Image.Height * (72.0 / info.Image.VerticalResolution))); gif.SetAbsolutePosition(1, 1); document.SetPageSize(new Rectangle(gif.ScaledWidth, gif.ScaledHeight)); document.NewPage(); pdfWriter.DirectContent.AddImage(gif); if (needRotate) { pdfWriter.AddPageDictEntry(PdfName.ROTATE, new PdfNumber(270)); } } catch (Exception ex) { Data.Env.WriteToLog(ex); return; } } document.Close(); } }
public void getTextToTable(string FileName) { try { System.IO.StreamReader sr = new System.IO.StreamReader(FileName); iTextSharp.text.Document doc = new iTextSharp.text.Document(); PdfWriter.GetInstance(doc, new System.IO.FileStream(FileName, System.IO.FileMode.Create)); doc.Open(); doc.Add(new iTextSharp.text.Paragraph(sr.ReadToEnd())); doc.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); throw new Exception(ex.Message); } }
static void Jpg2pdfConversion(string source, string imgextend) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(source); using (FileStream fs = new FileStream(source.Replace("." + imgextend, ".pdf"), FileMode.Create, FileAccess.Write, FileShare.None)) { using (iTextSharp.text.Document doc = new iTextSharp.text.Document(image)) { using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs)) { doc.Open(); image.SetAbsolutePosition(0, 0); writer.DirectContent.AddImage(image); doc.Close(); } } } }
private bool EncryptPDF(String strPath, String StrDesPath, String strOpenPassWord, String strOwnerPassWord) { try { PdfReader itextPdfReader = new PdfReader(strPath); iTextSharp.text.Document document = new iTextSharp.text.Document(); FileStream fileStream = new FileStream(StrDesPath, FileMode.Create); PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream); String strOpenPas, strOwnerPas; strOpenPas = this.OpenFilPassWText.Text; strOwnerPas = this.PerrmisionPassText.Text; pdfWriter.SetEncryption(PdfWriter.STRENGTH40BITS, strOpenPas, strOwnerPas, PdfWriter.AllowCopy); document.Open(); //Setting PDF file enctyption page count document.SetPageSize(iTextSharp.text.PageSize.LEDGER.Rotate()); iTextSharp.text.pdf.PdfContentByte oDirectContent = pdfWriter.DirectContent; int iNUmberOfPages = itextPdfReader.NumberOfPages; int iPage = 0; while (iPage < iNUmberOfPages) { iPage += 1; document.SetPageSize(itextPdfReader.GetPageSizeWithRotation(iPage)); document.NewPage(); iTextSharp.text.pdf.PdfImportedPage oPdfImportedPage = pdfWriter.GetImportedPage(itextPdfReader, iPage); int iRotation = itextPdfReader.GetPageRotation(iPage); if (iRotation == 90 || iRotation == 270) { oDirectContent.AddTemplate(oPdfImportedPage, 0, -1.0F, 1.0F, 0, 0, itextPdfReader.GetPageSizeWithRotation(iPage).Height); } else { oDirectContent.AddTemplate(oPdfImportedPage, 1.0F, 0, 0, 1.0F, 0, 0); } } document.Close(); return(true); }catch (Exception e) { //e.ToString(); return(false); } }
public void ExtractPage(string sourcePdfPath, string outputPdfPath, int pageNumber, int pageend) { iTextSharp.text.pdf.PdfReader reader = null; iTextSharp.text.Document document = null; iTextSharp.text.pdf.PdfCopy pdfCopyProvider = null; iTextSharp.text.pdf.PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the contents of the source Pdf file: reader = new iTextSharp.text.pdf.PdfReader(sourcePdfPath); // Capture the correct size and orientation for the page: document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(pageNumber)); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); document.Open(); // Extract the desired page number: if (pageNumber == pageend) { importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber + 1); pdfCopyProvider.AddPage(importedPage); } else { for (int i = pageNumber; i <= pageend; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i + 1); pdfCopyProvider.AddPage(importedPage); } } document.Close(); reader.Close(); } catch (Exception ex) { _arCommonService.CreateErrorLog(ex.Message, ex.StackTrace); } }
public static Byte[] GetCreatePdf() { var doc = new iTextSharp.text.Document(); var ms = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, ms); var random = new Random(); doc.Open(); for (var i = 0; i < 5; i++) { doc.Add(new iTextSharp.text.Paragraph(GetRandomString(random))); } doc.Close(); return(ms.ToArray()); }
/// <summary> /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf /// </summary> /// <param name="sFilename"></param> /// <returns></returns> static private string WriteCompatiblePdf(string sFilename) { string sNewPdf = HttpContext.Current.Server.MapPath("~/OrderReceipts") + @"\" + "NewAttachment_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".pdf"; 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); }
//to open pdf file public void openpdf() { string fn; fn = tbx.Text; string cipher = ""; try { var text = new StringBuilder(); PdfReader pdfr = new PdfReader(fn); for (int i = 1; i <= pdfr.NumberOfPages; i++) { ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); var currentText = PdfTextExtractor.GetTextFromPage(pdfr, i, strategy); currentText = Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText))); text.Append(currentText); } string pl = text.ToString(); string key = textBox1.Text; cipher = encrypt(pl); //saving pdf file string loc = ""; SaveFileDialog open = new SaveFileDialog(); if (open.ShowDialog() == DialogResult.OK) { loc = open.FileName + ".pdf"; } FileStream fs = new FileStream(loc, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document doc = new iTextSharp.text.Document(); iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); doc.Add(new para(cipher)); doc.Close(); } catch (Exception ex) { MessageBox.Show("Error Occured: " + ex.Message); } }
/// <summary> /// saveAsPDFToolStripMenuItem_Click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveAsPDFToolStripMenuItem_Click(object sender, EventArgs e) { var docContent = this.dockPanelEx1.FindActiveDocument(); if (docContent == null) { MessageBox.Show("请选择指纹采集工作区,然后在进行此操作。", "提示"); return; } var docCtrl = docContent as DocumentControl; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = Application.StartupPath; saveFileDialog1.FileName = docCtrl.ReportName; saveFileDialog1.Filter = "PDF|*.pdf"; saveFileDialog1.Title = "保存PDF"; var result = saveFileDialog1.ShowDialog(); if (DialogResult.OK == result && !string.IsNullOrEmpty(saveFileDialog1.FileName)) { if (docCtrl != null) { Bitmap bmp = new Bitmap((int)PrintHelper.MillimetreToPixel(GlobalSetting.DefaultPrintPageSizeMM.Width), (int)PrintHelper.MillimetreToPixel(GlobalSetting.DefaultPrintPageSizeMM.Height)); Graphics g = Graphics.FromImage(bmp); docCtrl.DrawReportImage(g); iTextSharp.text.Rectangle rr = new iTextSharp.text.Rectangle((int)PrintHelper.MillimetreToPixel(GlobalSetting.DefaultPrintPageSizeMM.Width), (int)PrintHelper.MillimetreToPixel(GlobalSetting.DefaultPrintPageSizeMM.Height)); iTextSharp.text.Document document = new iTextSharp.text.Document(rr); try { iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(saveFileDialog1.FileName, FileMode.CreateNew)); document.Open(); iTextSharp.text.Image sd = iTextSharp.text.Image.GetInstance(bmp as Image, ImageFormat.Bmp); document.Add(sd); } catch (Exception Ex) { MessageBox.Show(Ex.ToString()); } document.Close(); } } }
/// <summary> /// Create a new PDF document from contents /// </summary> /// <param name="path"></param> /// <param name="contents"></param> /// <param name="page"></param> /// <param name="marginLeft"></param> /// <param name="marginTop"></param> /// <param name="marginRight"></param> /// <param name="marginBottom"></param> public static void CreateNewPDF(string path, IEnumerable <object> contents, Content.Page page, double marginLeft = 5, double marginTop = 10, double marginRight = 5, double marginBottom = 10) { FileStream fs = new System.IO.FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document doc = new iTextSharp.text.Document(page.ToPDF()); PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.SetMargins((float)marginLeft, (float)marginRight, (float)marginTop, (float)marginBottom); doc.Open(); foreach (object content in contents) { var t = content.GetType(); if (content.GetType().GetInterfaces().Contains(typeof(Content.IPDFContent))) { if (content.GetType() == typeof(Content.PageBreak)) { doc.NewPage(); } else { Content.IPDFContent co = content as Content.IPDFContent; doc.Add(co.ToPDF()); } } else { if (content.GetType() == typeof(Geometries.PDFGeometry)) { Geometries.PDFGeometry l = (Geometries.PDFGeometry)content; l.ToPDF(writer); } else { doc.Add(new iTextSharp.text.Paragraph(content.ToString())); } } } doc.Close(); }
private byte[] GeneratePdf(List <iTextSharp.text.pdf.PdfPTable> lsPTables, ref StringBuilder sbLog) { byte[] btPdf = null; try { if (lsPTables != null && lsPTables.Count > 0) { try { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 40f, 40f, 30f, 10f); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream); /*<#PdfDocumentPageEvent#>*/ document.Open(); foreach (iTextSharp.text.pdf.PdfPTable tab1 in lsPTables) { document.Add(tab1); } document.Close(); btPdf = memoryStream.ToArray(); memoryStream.Close(); sbLog.AppendLine("PdfGen-doc: Success \r\n"); } } catch (Exception ex1) { sbLog.AppendLine("PdfGen-doc-Ex:" + ex1.Message + " \r\n"); } } } catch (Exception ex) { sbLog.AppendLine("PdfGen-Ex:" + ex.Message + " \r\n"); } return(btPdf); }
private System.IO.MemoryStream imposeTypesetPerfectBindBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var docB5 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(515.76f, 728.4f)); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB5, dest_stream); docB5.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (int i = 1; i <= reader.NumberOfPages; i++) { if (i != 1) { docB5.NewPage(); } docB5.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate t = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015 if (i % 2 == 1) { contentbyte.AddTemplate(t, /*42.5f*/ 35.5f, -141.75f); // position for front side of B5 sheet } else if (i % 2 == 0) { contentbyte.AddTemplate(t, /*110f*/ 110f, -141.75f); // position for back side of B5 sheet } } docB5.Close(); reader.Close(); writer.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
public void savepdf() { string loc = ""; SaveFileDialog open = new SaveFileDialog(); if (open.ShowDialog() == DialogResult.OK) { loc = open.FileName + ".pdf"; } //string fn = textBox2.Text; FileStream fs = new FileStream(loc, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Document doc = new iTextSharp.text.Document(); iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); doc.Add(new para(inputTextBox.Text)); doc.Close(); // MessageBox.Show("PDF file is saved"); }
private HttpResponseMessage GetPdfResponseForDictionary(Dictionary dictionary) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); var memoryStream = new MemoryStream(); iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream); document.Open(); string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont( ARIALUNI_TFF, iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL); uint rowNumber = 1; foreach (var phrasesPair in dictionary.PhrasesPairs.OrderBy(p => p.FirstPhrase.Text)) { document.Add(new iTextSharp.text.Paragraph( string.Format("{0}) {1} - {2}", rowNumber++, phrasesPair.FirstPhrase.Text, phrasesPair.SecondPhrase.Text), font)); } document.NewPage(); rowNumber = 1; foreach (var phrasesPair in dictionary.PhrasesPairs.OrderBy(p => p.SecondPhrase.Text)) { document.Add(new iTextSharp.text.Paragraph( string.Format("{0}) {1} - {2}", rowNumber++, phrasesPair.SecondPhrase.Text, phrasesPair.FirstPhrase.Text), font)); } document.AddAuthor(dictionary.OwnerId); document.Close(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new ByteArrayContent(memoryStream.ToArray()); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); string filename = string.Format("{0}.pdf", dictionary.Name); response.Content.Headers.ContentDisposition.FileName = Uri.EscapeUriString(filename); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return(response); }
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 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()); } }
public static string Create_Invoice(string content, string id) { var invoice_path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Resources", "Invoice", string.Format("{0}.pdf", id)); if (!File.Exists(invoice_path)) { var file = File.Create(invoice_path); file.Close(); } using (FileStream file = new FileStream(invoice_path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { StringReader sr = new StringReader(content); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 35f, 0f); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, file); pdfDoc.Open(); iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr); pdfDoc.Close(); file.Close(); } return(string.Format("/Resources/Invoice/{0}.pdf", id)); }
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(); }
// 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(); }
public System.Web.Mvc.FileResult ExportPdf(long DocumentID) { iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 50, 20, 70); MemoryStream output = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, output); long userId = Convert.ToInt64(HttpContext.User.Identity.Name); OpenBookSystemMVC.OBISReference.Document doc = null; OBSDataSource.GetDocument(DocumentID, out doc); AccountInfo ai = null; OBSDataSource.GetUserProfile(userId, out ai); if (doc == null || ai == null) { return null; } string returnContent = doc.SimplifiedContent; if (ai.Preferences.DocumentFontSize == 0) { returnContent = returnContent.ToUpper(); } pdfDoc.Open(); iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); if (ai.Preferences != null) { iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/verdana.ttf"), "Verdana"); iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/times.ttf"), "Times New Roman"); iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/calibri.ttf"), "Calibri"); iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/tahoma.ttf"), "Tahoma"); iTextSharp.text.Font font = iTextSharp.text.FontFactory.GetFont( ai.Preferences.DocumentFontName, ai.Preferences.DocumentFontSize > 0 ? ai.Preferences.DocumentFontSize : 18); ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.FACE, ai.Preferences.DocumentFontName); } else { ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.FACE, "Times New Roman"); } ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.ENCODING, BaseFont.IDENTITY_H); List<iTextSharp.text.IElement> htmlElements = HTMLWorker.ParseToList(new StringReader(returnContent), ST); FormatImgElements(htmlElements); foreach (var item in htmlElements) { pdfDoc.Add(item); } pdfDoc.Close(); var bytes = output.ToArray(); return File(bytes, "application/pdf", string.Format("{0}.pdf", doc.Title)); }
// public List<Card> Cards { get; set; } public void tiffToPDF(string resultPDF) { // creation of the document with a certain size and certain margins using (iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0)) { using (FileStream fs = new System.IO.FileStream(resultPDF, System.IO.FileMode.Create)) { // creation of the different writers using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs)) { document.Open(); foreach (Page page in Pages) { if (page.Card.ImageLocationLR != null) { // load the tiff image and count the total pages int total = 0; using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(page.Card.ImageLocationLR)) { total = bm2.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); // bm2 = null; bm2.Dispose(); } for (int k = 0; k < total; ++k) { System.Drawing.Bitmap bm = new System.Drawing.Bitmap(page.Card.ImageLocationLR); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp); img.ScaleToFitHeight = false; img.ScalePercent(70f / img.DpiX * 100); // scale the image to fit in the page //Lukas old value img.SetAbsolutePosition(-22, 25); img.SetAbsolutePosition(0, 0); cb.AddImage(img); document.NewPage(); img = null; cb.ClosePath(); bm.Dispose(); } } } document.Close(); document.Dispose(); writer.Dispose(); fs.Close(); fs.Dispose(); } } } }
public 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(); } }
// 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> /// 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(); } }
/// <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(); }
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(); }
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(); } } }
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 static void CombineMultiplePDFs(string[] fileNames, string outFile) { try { iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return; } document.Open(); foreach (string fileName in fileNames) { if (System.IO.File.Exists(fileName)) { PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyDocumentFields(reader); } reader.Close(); } } writer.Close(); document.Close(); } catch { MessageBox.Show("Close the pdf file and try again."); } }
public 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 }
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"); } } }
protected void OnButtonPDFClicked(object sender, EventArgs e) { FileChooserDialog fc= new FileChooserDialog("Укажите файл для сохранения документа", this, FileChooserAction.Save, "Отмена",ResponseType.Cancel, "Сохранить",ResponseType.Accept); fc.CurrentName = DocInfo.TypeName + " " + entryNumber.Text + ".pdf"; fc.Show(); if(fc.Run() == (int) ResponseType.Accept) { fc.Hide(); iTextSharp.text.Document document = new iTextSharp.text.Document(); using (var stream = new FileStream(fc.Filename, FileMode.Create, FileAccess.Write, FileShare.None)) { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); document.Open(); foreach(DocumentImage img in Images) { if(img.Image.Width > img.Image.Height) document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); else document.SetPageSize(iTextSharp.text.PageSize.A4); document.NewPage(); var image = iTextSharp.text.Image.GetInstance(img.file); image.SetAbsolutePosition(0,0); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); } } fc.Destroy(); }
/// <summary> /// Merge CV and covering letter and return pdf location /// </summary> /// <param name="filesToMerge"></param> /// <param name="outputFilename"></param> /// <param name="result"></param> public static void MergePdf(IEnumerable<BulkPrintDocEntry> filesToMerge, string outputFilename, ref BulkPrintCvResult result) { result.ErrorCvs = new List<BulkPrintErrorCvs>(); var bulkPrintDocEntries = filesToMerge as BulkPrintDocEntry[] ?? filesToMerge.ToArray(); if (!bulkPrintDocEntries.Any()) return; var document = new iTextSharp.text.Document(); // initialize pdf writer var writer = PdfWriter.GetInstance(document, new FileStream(outputFilename, FileMode.Create)); // open document to write document.Open(); var content = writer.DirectContent; foreach (var docEntry in bulkPrintDocEntries) { var sCoveringLetterHtml = docEntry.CoveringLetterHtml; // create page document.NewPage(); // add styles var styles = new StyleSheet(); styles.LoadStyle("left", "width", "22%"); styles.LoadTagStyle("td", "valign", "top"); styles.LoadStyle("bordered", "border", "1"); var hw = new HTMLWorker(document, null, styles); hw.Parse(new StringReader(sCoveringLetterHtml)); var sFileName = docEntry.CvFileName.ToLower().Replace(".docx", ".pdf").Replace(".DOCX", ".pdf").Replace(".doc", ".pdf").Replace(".DOC", ".pdf").Replace(".rtf", ".pdf").Replace(".RTF", ".pdf"); if (!File.Exists(sFileName)) { //pdf file not exists result.ErrorCvs.Add(new BulkPrintErrorCvs { Error = "Pdf file does not exists. " + sFileName, ContactId = docEntry.ContactId, ContactName = new Contacts().GetCandidateName(docEntry.ContactId), Document = docEntry.Doc }); continue; } // Create pdf reader var reader = new PdfReader(sFileName); if (!reader.IsOpenedWithFullPermissions) { //pdf file does not have permission result.ErrorCvs.Add(new BulkPrintErrorCvs { Error = "Do not have enough permissions to read the file", ContactId = docEntry.ContactId, ContactName = new Contacts().GetCandidateName(docEntry.ContactId), Document = docEntry.Doc }); continue; } var numberOfPages = reader.NumberOfPages; // Iterate through all pages for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { // Determine page size for the current page document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex)); // Create page document.NewPage(); var importedPage = writer.GetImportedPage(reader, currentPageIndex); // Determine page orientation var pageOrientation = reader.GetPageRotation(currentPageIndex); switch (pageOrientation) { case 90: content.AddTemplate(importedPage, 0, -1, 1, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height); break; case 270: content.AddTemplate(importedPage, 0, 1, -1, 0, reader.GetPageSizeWithRotation(currentPageIndex).Width, 0); break; default: content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0); break; } } } document.Close(); }
/// <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) { //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 createPDF(Stream output) { //PrimaryAntibody tempAntibody = myConn.getPrimaryAntibodyByID(Convert.ToInt16(Request.QueryString["id"])); PrimaryAntibody tempAntibody = myConn.getPrimaryAntibodyByID(int.Parse(txtid.Value)); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=primary_antibody_" + tempAntibody.id + ".pdf"); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 72, 72, 72, 72); PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream); document.Open(); //Page title and spacing iTextSharp.text.Chunk pageTitle = new iTextSharp.text.Chunk("Primary Antibody Record", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20)); document.Add(pageTitle); iTextSharp.text.Paragraph spacing = new iTextSharp.text.Paragraph(" "); document.Add(spacing); //Name iTextSharp.text.Paragraph tempParagraph = new iTextSharp.text.Paragraph(); iTextSharp.text.Chunk tempLabel = new iTextSharp.text.Chunk("Name: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); iTextSharp.text.Chunk tempValue = new iTextSharp.text.Chunk(tempAntibody.name, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Type tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Type: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.type, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Clone tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Clone: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.clone, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Host Species tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Host Species: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.hostSpecies, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Reactive Species tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Reactive Species: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.reactiveSpecies, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Concentration tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Concentration: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.concentration, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Working Dilution tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Working Dilution: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.workingDilution, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Applications tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Applications: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.applications, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Isotype tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Isotype: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.isotype, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Antigen tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Antigen: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.antigen, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); //Fluorophore tempParagraph = new iTextSharp.text.Paragraph(); tempLabel = new iTextSharp.text.Chunk("Fluorophore: ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempValue = new iTextSharp.text.Chunk(tempAntibody.fluorophore, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10)); tempParagraph.Add(tempLabel); tempParagraph.Add(tempValue); document.Add(tempParagraph); document.Close(); }
protected void 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(); }
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 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); } }
void SavePDF() { iTextSharp.text.Document document = new iTextSharp.text.Document(); using (var stream = new MemoryStream ()) { var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); foreach(Pixbuf pix in vimageslist1.Images) { if(pix.Width > pix.Height) document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); else document.SetPageSize(iTextSharp.text.PageSize.A4); document.NewPage(); var image = iTextSharp.text.Image.GetInstance(pix.SaveToBuffer ("jpeg")); image.SetAbsolutePosition(0,0); image.ScaleToFit(document.PageSize.Width, document.PageSize.Height); document.Add(image); } document.Close(); stream.Position = 0; File = stream.ToArray (); } }
public static 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(); }