public void Gerar(string tituloDoDocumento, string nome = null, string cpf = null, string hash = null) { string fileName = Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf"; this.pageState = new CustomPageState(); //string fileName = System.Reflection.Assembly.GetEntryAssembly().Location + "\\" + string.Format("{0}.pdf", DateTime.Now.ToString(@"yyyyMMdd") + "_" + DateTime.Now.ToString(@"HHmmss")); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { //criando e estipulando o tipo da folha usada using (pdfDoc = new Document(PageSize.A4)) { try { //adcionando data de criação pdfDoc.AddCreationDate(); //criando pdf em branco no disco pdfWriter = PdfWriter.GetInstance(pdfDoc, fs); //atrelando a classe de eventos da pagina if (string.IsNullOrEmpty(nome) || string.IsNullOrEmpty(cpf) || string.IsNullOrEmpty(hash)) { //estibulando o espaçamento das margens que queremos pdfDoc.SetMargins(40, 40, 60, 50); //para documentos não assinados pdfWriter.PageEvent = new CabecalhoDocumentoNaoAssinado(tituloDoDocumento); } else { //estibulando o espaçamento das margens que queremos pdfDoc.SetMargins(40, 40, 60, 80); //para documentos assinados pdfWriter.PageEvent = new CabecalhosDocumentoAssinado(tituloDoDocumento, nome, cpf, hash, pageState); } //ABRINDO DOCUMENTO PARA ALTERAÇÕES pdfDoc.Open(); //Corpo do documento Documento(); //identificando a última página this.pageState.IsLastPage = true; //fecha pdf if (pdfDoc.IsOpen()) { pdfDoc.Close(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } if (File.Exists(fileName)) { System.Diagnostics.Process.Start(fileName); } }
/* Bugünkü Kelimeleri Pdf Olustur*/ private void button2_Click(object sender, EventArgs e) { string wordsList = "Ingilizce Kelimeler\n------------------------------------\n"; foreach (var item in words.Where(x => x.Date == DateTime.Now.ToShortDateString())) { wordsList += item.Title + " : " + item.Mean + "\n"; } try { Document pdfDosya = new Document(); PdfWriter.GetInstance(pdfDosya, new FileStream("C:KelimeListesiGunluk.pdf", FileMode.Create)); pdfDosya.Open(); pdfDosya.AddCreator("berke kurnaz"); pdfDosya.AddCreationDate(); pdfDosya.AddAuthor("Berke Kurnaz"); pdfDosya.AddHeader("Bütün Kelimeler", "İngilizce Kelime Uygulaması"); pdfDosya.AddTitle("Bütün Kelimeler"); Paragraph eklenecekMetin = new Paragraph(wordsList); pdfDosya.Add(eklenecekMetin); pdfDosya.Close(); MessageBox.Show("Pdf Dosyası Oluşturuldu."); } catch { MessageBox.Show("Hata Oluştu"); } }
/// <summary> /// 文件右击属性 /// </summary> /// <param name="Author">作者</param> /// <param name="CreationDate">是否添加创建日期</param> /// <param name="Creator">创建者</param> /// <param name="Subject">主题</param> /// <param name="Title">标题</param> /// <param name="Keywords">关键字</param> /// <param name="Header">自定义头名称</param> /// <param name="content">自定义头内容</param> public void AddFileAttributes(string Author, bool?CreationDate, string Creator, string Subject, string Title, string Keywords, string Header, string content) { if (Author != null) { document.AddAuthor(Author); } if (CreationDate != null) { document.AddCreationDate(); } if (Creator != null) { document.AddCreator(Creator); } if (Subject != null) { document.AddSubject(Subject); } if (Title != null) { document.AddTitle(Title); } if (Keywords != null) { document.AddKeywords(Keywords); } if (Header != null && content != null) { document.AddHeader(Header, content); } }
protected void Init(String fileName, String title = "", String author = "webhost") { if (Initialized) { throw new WebhostException("This PDFPublisher is already initialized."); } FileName = fileName; if (fileName.StartsWith("~/")) { fileName = HttpContext.Current.Server.MapPath(fileName); } if (File.Exists(fileName)) { File.Delete(fileName); } document = new Document(PageSize.LETTER, SideMargin, SideMargin, TopMargin, BottomMargin); writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.OpenOrCreate)); document.Open(); document.AddCreationDate(); document.AddAuthor(author); document.AddCreator("webhost.dublinschool.org"); document.AddTitle(title); Initialized = true; }
public static MemoryStream Create(string conteudo, string titulo, string assunto) { MemoryStream ms = new MemoryStream(); using (TextReader textReader = new StringReader(conteudo)) { Document document = new Document(PageSize.A4, 40, 40, 30, 30); PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms); document.AddAuthor("Safe Life"); document.AddCreationDate(); document.AddTitle(titulo); document.AddCreator("Safe Life"); document.AddSubject(assunto); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); pdfWriter.SetEncryption(null, encoding.GetBytes("sAfelIfe2017*"), PdfWriter.ALLOW_PRINTING, PdfWriter.STRENGTH128BITS); pdfWriter.CloseStream = false; HTMLWorker htmlWorker = new HTMLWorker(document); document.Open(); htmlWorker.StartDocument(); htmlWorker.Parse(textReader); htmlWorker.EndDocument(); htmlWorker.Close(); document.Close(); } ms.Position = 0; return(ms); }
private void To_pdf() { Document doc = new Document(PageSize.LETTER, 10f, 10f, 10f, 0f); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance("LogoCepeda.png"); image1.ScaleAbsoluteWidth(140); image1.ScaleAbsoluteHeight(70); saveFileDialog1.InitialDirectory = @"C:"; saveFileDialog1.Title = "Guardar Reporte"; saveFileDialog1.DefaultExt = "pdf"; saveFileDialog1.Filter = "pdf Files (*.pdf)|*.pdf| All Files (*.*)|*.*"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; string filename = "Reporte de Movimiento de Caja" + DateTime.Now.ToString(); if (saveFileDialog1.ShowDialog() == DialogResult.OK) { filename = saveFileDialog1.FileName; if (filename.Trim() != "") { FileStream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); PdfWriter.GetInstance(doc, file); doc.Open(); string remito = lblLogo.Text; string ubicado = lblDir.Text; string envio = "Fecha : " + DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year; Chunk chunk = new Chunk(remito, FontFactory.GetFont("ARIAL", 16, iTextSharp.text.Font.BOLD, color: BaseColor.BLUE)); doc.Add(new Paragraph(" " + envio, FontFactory.GetFont("ARIAL", 7, iTextSharp.text.Font.ITALIC))); doc.Add(image1); doc.Add(new Paragraph(chunk)); doc.Add(new Paragraph(ubicado, FontFactory.GetFont("ARIAL", 9, iTextSharp.text.Font.NORMAL))); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Reporte de Movimientos de Caja ")); doc.Add(new Paragraph(" ")); GenerarDocumento(doc); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Reporte de Gastos del Dia ")); doc.Add(new Paragraph(" ")); GenerarDocumentogastos(doc); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Totales de Pagos :" + lbling.Text)); doc.Add(new Paragraph("Totales de Gastos :" + lbldeu.Text)); doc.Add(new Paragraph("Totales Final :" + lbltotal.Text)); doc.AddCreationDate(); doc.Close(); Process.Start(filename);//Esta parte se puede omitir, si solo se desea guardar el archivo, y que este no se ejecute al instante } } else { MessageBox.Show("No guardo el Archivo"); } }
private void Speichern(string filename) { try { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.AddTitle("Webfuzzer Report"); document.AddCreationDate(); document.Open(); document.Add(new Paragraph("WebFuzzer Found URLs", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16, iTextSharp.text.Font.UNDERLINE))); document.Add(new Paragraph(" ")); foreach (ListViewItem item in listViewResult.Items) { document.Add(new Paragraph(item.SubItems[1].Text)); if (richTextBoxPOST.Text != string.Empty) { document.Add(new Paragraph("POST data: " + richTextBoxPOST.Text)); } document.Add(new Paragraph(" ")); } document.Close(); } catch (IOException) { MessageBox.Show("The file is in use. Please close all applications accessing this file and try again.", "Access not possible", MessageBoxButtons.OK); } catch (Exception ex) { Console.WriteLine("Fehler beim Speichern" + ex); } }
public Document CriarDocumentoPDF(Boolean exameOuMedicamento) { Document doc = new Document(PageSize.A4); doc.SetMargins(40, 40, 40, 80); doc.AddCreationDate(); if (exameOuMedicamento) { doc.AddTitle("Receita Exame"); doc.AddSubject("Receita impressa, Sistema de Gerenciamento da Clínica"); doc.AddKeywords("receita, exame, sistema de gerenciamento da clínica"); doc.AddCreator("Sistema de Gerenciamento da Clínica"); doc.AddAuthor("Sistema Interno do Sistema de Gerenciamento da Clínica"); doc.AddHeader("Teste1", "teste 2"); } else { doc.AddTitle("Receita Medicamento"); doc.AddSubject("Receita impressa, Sistema de Gerenciamento da Clínica"); doc.AddKeywords("receita, exame, sistema de gerenciamento da clínica"); doc.AddCreator("Sistema de Gerenciamento da Clínica"); doc.AddAuthor("Sistema Interno do Sistema de Gerenciamento da Clínica"); doc.AddHeader("Teste3", "teste 4"); } return(doc); }
public static void gerarPDF(string path) { FileInfo dir = new FileInfo(path); StringBuilder texto = new StringBuilder(); FileInfo fl = new FileInfo(path); fl.GetAccessControl(); DirectoryInfo pir = new DirectoryInfo(fl.FullName.ToString()); string[] lines = System.IO.File.ReadAllLines(path); Document doc = new Document(iTextSharp.text.PageSize.A4); doc.SetMargins(40, 40, 40, 80); doc.AddCreationDate(); string caminho = fl.FullName + ".pdf"; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create)); doc.Open(); string dados = ""; foreach (string line in lines) { Paragraph paragrafo = new Paragraph(dados); paragrafo.Add(line.ToString()); doc.Add(paragrafo); } doc.Close(); System.Diagnostics.Process.Start(caminho); }
static void Main(string[] args) { Document doc = new Document(PageSize.A4); //criando e estipulando o tipo da folha usada doc.SetMargins(40, 40, 40, 80); //estibulando o espaçamento das margens que queremos doc.AddCreationDate(); //adicionando as configuracoes //caminho onde sera criado o pdf + nome desejado //OBS: o nome sempre deve ser terminado com .pdf string caminho = @"" + "CONTRATO.pdf"; //criando o arquivo pdf embranco, passando como parametro a variavel //doc criada acima e a variavel caminho //tambem criada acima. PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create)); doc.Open(); //criando uma string vazia string dados = ""; //criando a variavel para paragrafo Paragraph paragrafo = new Paragraph(dados, new Font(Font.NORMAL, 14)); //etipulando o alinhamneto paragrafo.Alignment = Element.ALIGN_JUSTIFIED; //Alinhamento Justificado //adicioando texto paragrafo.Add("TESTE TESTE TESTE"); //acidionado paragrafo ao documento doc.Add(paragrafo); //fechando documento para que seja salva as alteraçoes. doc.Close(); }
/// <summary> /// Render all data add and writes it to the specified writer /// </summary> /// <param name="model"> /// The model to render /// </param> /// <param name="os"> /// The output to write to /// </param> public override void RenderAllTables(IDataSetModel model, Stream os) { // TODO check the number of horizontal & vertical key values to determine the orientation of the page var doc = new Document(this._pageSize, 80, 50, 30, 65); // This doesn't seem to do anything... doc.AddHeader(Markup.HTML_ATTR_STYLESHEET, "style/pdf.css"); doc.AddCreationDate(); doc.AddCreator("NSI .NET Client"); try { PdfWriter.GetInstance(doc, os); doc.Open(); this.WriteTableModels(model, doc); } catch (DocumentException ex) { Trace.Write(ex.ToString()); LogError.Instance.OnLogErrorEvent(ex.ToString()); } catch (DbException ex) { Trace.Write(ex.ToString()); LogError.Instance.OnLogErrorEvent(ex.ToString()); } finally { if (doc.IsOpen()) { doc.Close(); } } }
public GerarPDF(string pCaminhoArquivoPDF) { _document = new Document(PageSize.A4); //Criando e estipulando o tipo da folha usada _document.SetMargins(40, 40, 40, 80); //estibulando o espaçamento das margens que queremos _document.AddCreationDate(); //adicionando as configuracoes _pdfWriter = PdfWriter.GetInstance(_document, new FileStream(pCaminhoArquivoPDF, FileMode.Create)); // Pegando a instancia do PDF Writer }
public void CriarProva(Prova prova, string path) { _document = new Document(PageSize.A4); //Criando e estipulando o tipo da folha usada _bold = new Font(Font.NORMAL, 14, (int)System.Drawing.FontStyle.Bold); _pdfWriter = PdfWriter.GetInstance(_document, new FileStream(path, FileMode.Create)); // Pegando a instancia do PDF Writer _document.SetMargins(40, 40, 40, 80); //estibulando o espaçamento das margens que queremos _document.AddCreationDate(); //adicionando as configuracoes _document.Open(); Write("Escola de Educação Básica Mariana R. T."); Write("Data: ....../....../......"); Write("Nome: Nota:"); Write("Matéria: " + prova.Materia.Nome); Write(string.Format("Disciplina: {0} Série: {1}", prova.Disciplina.Nome, prova.Serie)); Write("\n"); WriteTitulo(string.Format("Prova de {0}", prova.Materia.Nome)); Write("\n"); MontarQuestoes(prova.Questoes); _document.Add(Chunk.NEXTPAGE); WriteTitulo(string.Format("Gabarito - {0}", prova.Materia.Nome)); Write("\n"); MontarGabarito(prova.Questoes); _document.Close(); }
private void Speichern(string filename) { try { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.AddTitle("Authentication Report"); document.AddCreationDate(); document.Open(); document.Add(new Paragraph("Authentication Tester: User/Password List", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16, iTextSharp.text.Font.UNDERLINE))); document.Add(new Paragraph(" ")); document.Add(new Paragraph("From: " + textBoxURL.Text)); document.Add(new Paragraph(" ")); foreach (ListViewItem item in listViewAuths.Items) { document.Add(new Paragraph("Username: "******"Password: "******" ")); } document.Close(); } catch (IOException) { MessageBox.Show("The file is in use. Please close all applications accessing this file and try again.", "Access not possible", MessageBoxButtons.OK); } catch (Exception ex) { Console.WriteLine("Fehler beim Speichern" + ex); } }
void generatePDFDocument(FileStream fs, IDictionary <string, List <FullFilePath> > modelMap) { Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50); PdfWriter writer = PdfWriter.GetInstance(doc, fs); List <string> models = new List <string>(); try { models.AddRange(modelMap.Keys); models.Sort(); doc.AddAuthor("rik-author"); doc.AddCreationDate(); doc.AddCreator("rik-creator"); doc.AddHeader("header-name", "header content"); doc.AddKeywords("kw1 kw2 kw3 kw4"); doc.AddLanguage("english"); doc.AddProducer(); doc.AddSubject("a subject"); doc.AddTitle("title"); doc.Open(); generateIndex(doc, models); generateModelTables(modelMap, doc, models); doc.Close(); } catch (Exception ex) { Logger.log(MethodBase.GetCurrentMethod(), ex); } }
private void CreateDocument() { if (_doc != null) { return; } _doc = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN); _doc.AddCreator(_domain); _doc.AddAuthor(_domain); _doc.AddSubject(_subject); _doc.AddCreationDate(); _stream = new MemoryStream(); _writer = PdfWriter.GetInstance(_doc, _stream); _writer.PageEvent = new PageEvents(_domain, _baseFont); _doc.Open(); /*var logoTable = new PdfPTable(2); * logoTable.HorizontalAlignment = Element.ALIGN_LEFT; * logoTable.SetWidths(new[] {5, 100}); * * Image logoImage = Image.GetInstance(_logoPath); * logoImage.ScalePercent(60); * var iconCell = new PdfPCell(logoImage) {Border = 0, VerticalAlignment = Element.ALIGN_MIDDLE}; * logoTable.AddCell(iconCell); * * var logoText = new Phrase("Study fun", CreateFont(18)); * var logoTextCell = new PdfPCell(logoText) {Border = 0}; * logoTable.AddCell(logoTextCell); * * _doc.Add(logoTable);*/ }
/// <summary> /// Este metodo nos permite crear una archivo PDF /// con el ticket de compra donde mostramos /// los datos de la tineda /// los aticulos vendidos /// etc. /// </summary> private void To_pdf() { Document doc = new Document(PageSize.A5, 10, 10, 10, 10); //Variable de tipo documento y su instancia SaveFileDialog saveFileDialog1 = new SaveFileDialog(); //instancia para guardar los datos string path = Directory.GetCurrentDirectory(); saveFileDialog1.InitialDirectory = path; saveFileDialog1.Title = "Ticket"; //Titulo del documento saveFileDialog1.DefaultExt = "pdf"; //Extencion del documento saveFileDialog1.Filter = "pdf Files (*.pdf)|*.pdf| All Files (*.*)|*.*"; //Tipo de archivo saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; FileStream file = new FileStream("Ticket.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); //Creamos y escribimos en el PDF PdfWriter.GetInstance(doc, file); doc.Open(); //Abrimos el docuemnto string remito = "Empleado: " + ID_emp_tex.Text; string fecha = "Fecha:" + DateTime.Now.ToString(); /* * En las siguientes lineas creamos el diseño del boleto que se imprimira */ Chunk chunk = new Chunk("Tienda de abarrotes \"Los Pinos\" ", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD)); doc.Add(new Paragraph(chunk)); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph("San Luis Potosí, San Luis Potosí")); doc.Add(new Paragraph("Dirección: Zaragoza #523")); doc.Add(new Paragraph("Teléfono: (444)-507-66-83")); doc.Add(new Paragraph("E-mail: [email protected]")); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(remito)); doc.Add(new Paragraph(fecha)); doc.Add(new Paragraph("Caja: 1")); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Cantidad" + " " + "Artículo" + " " + "Subtotal" + " " + "Total")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(articulos)); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Total de la venta: $ " + Total)); doc.Add(new Paragraph("Pago un total de: $ " + total_box.Text)); doc.Add(new Paragraph("Cambio: $ " + cambi)); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.AddCreationDate(); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" Gracias por su preferencia ")); doc.Add(new Paragraph("__________________________________", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD))); doc.Close(); Process.Start("Ticket.pdf"); //Esta parte se puede omitir, si solo se desea guardar el archivo, y que este no se ejecute al instante }
public static void CreatePdf(string destinationFileName, string imageFilePath, CreationInfo info) { Image gif = Image.GetInstance(imageFilePath); Document doc = new Document(new Rectangle(gif.Width, gif.Height), 25, 25, 25, 25); try { var pdfWriter = PdfWriter.GetInstance(doc, new FileStream(destinationFileName, FileMode.Create)); pdfWriter.SetFullCompression(); pdfWriter.StrictImageSequence = true; pdfWriter.SetLinearPageMode(); doc.Open(); doc.AddTitle(info.Title); doc.AddSubject(info.Subject); doc.AddAuthor(info.Author); doc.AddCreator(info.Creator); doc.AddCreationDate(); doc.AddProducer(); doc.Add(gif); } finally { doc.Close(); } }
/// <summary>Exporta o texto para um arquivo PDF. </summary> public void Create(string text) { var saveFileDialog = new SaveFileDialog() { FileName = "imageReader", Filter = "PDF Documents | *.pdf" }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string documentFilePath = saveFileDialog.FileName; documentFilePath = documentFilePath.Replace(".pdf", ""); documentFilePath = documentFilePath + ".pdf"; var document = new Document(PageSize.A4); //criando e estipulando o tipo da folha usada document.SetMargins(40, 40, 40, 80); //estibulando o espaçamento das margens document.AddCreationDate(); //adicionando as configuracoes //criando o arquivo pdf em branco var writer = PdfWriter.GetInstance(document, new FileStream(documentFilePath, FileMode.Create)); document.Open(); var paragrafo = new Paragraph(text, new Font(Font.NORMAL, 14)) { Alignment = Element.ALIGN_JUSTIFIED }; document.Add(paragrafo); document.Close(); } }
public byte[] ExchangeNote(string sTitulo) { var pdfStream = new MemoryStream(); pdfFile = new Document(iTextSharp.text.PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(pdfFile, pdfStream); writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); writer.CompressionLevel = PdfStream.BEST_COMPRESSION; //writer.SetFullCompression(); pdfFile.Open(); //pdfFile.PageSize.BackgroundColor = new BaseColor(255,255,255); pdfFile.PageSize.Rotate(); pdfFile.AddAuthor("DeltaSoft"); pdfFile.AddCreator("DeltaSoft"); pdfFile.AddCreationDate(); pdfFile.AddTitle(sTitulo); //pdfFile.AddSubject(subject); //pdfFile.AddKeywords(sb.ToString()); fontBase = new iTextSharp.text.Font(FontFactory.GetFont(FontFactory.COURIER, 9, iTextSharp.text.Font.NORMAL)); fontTitulos = new iTextSharp.text.Font(FontFactory.GetFont(FontFactory.COURIER, 10, iTextSharp.text.Font.BOLD)); fontFields = new iTextSharp.text.Font(FontFactory.GetFont(FontFactory.COURIER, 9, iTextSharp.text.Font.BOLD)); ExchangeNote(); pdfFile.Close(); return(pdfStream.ToArray()); }
public static void ExportarPDF(DataTable DTCENTROS, Font normalFont) { // Creao el documento string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf"; Document doc = new Document(PageSize.A4, 50, 50, 25, 25); PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create)); // Le coloco el título y el autor doc.AddTitle("Centros"); doc.AddCreator(Program.cUsuario); //hacemos que se inserte la fecha de creación para el documento doc.AddCreationDate(); // Abro el archivo doc.Open(); // Escribos el encabezamiento en el documento //doc.Add(new Paragraph(Fecha)); doc.Add(Chunk.NEWLINE); // Creos una tabla que contendrá los datos PdfPTable tblPrueba = new PdfPTable(2); tblPrueba.WidthPercentage = 100; // Configuros el título de las columnas de la tabla PdfPCell clIdAsignaturas = new PdfPCell(new Phrase("IdAsignaturas", normalFont)); clIdAsignaturas.BorderWidth = 1; clIdAsignaturas.BorderWidthBottom = 0.55f; PdfPCell clNombre = new PdfPCell(new Phrase("Nombre", normalFont)); clNombre.BorderWidth = 1; clNombre.BorderWidthBottom = 0.55f; try { foreach (DataRow Row in DTCENTROS.Rows) { // Añado las celdas a la tabla tblPrueba.AddCell(clIdAsignaturas); tblPrueba.AddCell(clNombre); // Lleno la tabla con información clIdAsignaturas = new PdfPCell(new Phrase(Row["IdAsignaturas"].ToString(), normalFont)); clIdAsignaturas.BorderWidth = 0; clNombre = new PdfPCell(new Phrase(Row["Nombre"].ToString(), normalFont)); clNombre.BorderWidth = 0; } // Relleno la tabla con información, en caso de nuevos alumnos tblPrueba.AddCell(clIdAsignaturas); tblPrueba.AddCell(clNombre); // Finalmente, añado la tabla al documento PDF y lo abro doc.Add(tblPrueba); doc.Close(); Process prc = new System.Diagnostics.Process(); prc.StartInfo.FileName = fileName; prc.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private byte[] ReportPDF() { var memoryStream = new MemoryStream(); // Marge in centimeter, then I convert with .ToDpi() float margeLeft = 1.5f; float margeRight = 1.5f; float margeTop = 1.0f; float margeBottom = 1.0f; Document pdf = new Document( PageSize.A4, margeLeft.ToDpi(), margeRight.ToDpi(), margeTop.ToDpi(), margeBottom.ToDpi() ); pdf.AddTitle("Blazor-PDF"); pdf.AddAuthor("Ozzvy"); pdf.AddCreationDate(); pdf.AddKeywords("blazor"); pdf.AddSubject("Create a pdf file with iText"); PdfWriter writer = PdfWriter.GetInstance(pdf, memoryStream); //HEADER and FOOTER var fontStyle = FontFactory.GetFont("Arial", 16, BaseColor.White); var labelHeader = new Chunk("User Info", fontStyle); HeaderFooter header = new HeaderFooter(new Phrase(labelHeader), false) { BackgroundColor = new BaseColor(48, 79, 254), Alignment = Element.ALIGN_CENTER, Border = Rectangle.NO_BORDER }; //header.Border = Rectangle.NO_BORDER; pdf.Header = header; var labelFooter = new Chunk("Page", fontStyle); HeaderFooter footer = new HeaderFooter(new Phrase(labelFooter), true) { Border = Rectangle.NO_BORDER, Alignment = Element.ALIGN_RIGHT }; pdf.Footer = footer; pdf.Open(); if (_pagenumber == 1) { UserPrint.PageText(pdf, _user); } pdf.Close(); return(memoryStream.ToArray()); }
private void PdF() { Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = @"C:"; saveFileDialog1.Title = "Guardar Reporte"; saveFileDialog1.DefaultExt = "pdf"; saveFileDialog1.Filter = "pdf Files (*.pdf)|*.pdf| All Files (*.*)|*.*"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; string filename = ""; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { filename = saveFileDialog1.FileName; } if (filename.Trim() != "") { FileStream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); PdfWriter.GetInstance(doc, file); doc.Open(); string remito = "Autorizo: Juanelc197"; string envio = "Fecha:" + DateTime.Now.ToString(); Chunk chunk = new Chunk("DELSEL", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD)); doc.Add(new Paragraph(chunk)); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph("N.L")); doc.Add(new Paragraph(remito)); doc.Add(new Paragraph(envio)); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Nombre del Cliente: " + txt_nombre.Text)); doc.Add(new Paragraph("Forma de Pago: " + comboFormadePago.Text)); doc.Add(new Paragraph("Telefono: " + txt_telefono.Text)); doc.Add(new Paragraph("RFC: " + txt_rfc.Text)); doc.Add(new Paragraph(" ")); GenerarDocumento(doc); doc.AddCreationDate(); //doc.Add(new Paragraph("______________________________________________", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD))); //doc.Add(new Paragraph("Firma", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD))); doc.Add(new Paragraph("SubTotal: " + "$" + txt_subtotal.Text)); doc.Add(new Paragraph("IVA: " + txt_iva.Text + "%")); doc.Add(new Paragraph("Total: " + "$" + txt_total.Text)); doc.Add(new Paragraph("Total en letra: " + lbl_letra.Text)); doc.Add(new Paragraph("Forma de Pago: " + comboFormadePago.Text)); doc.Close(); Process.Start(filename);//Esta parte se puede omitir, si solo se desea guardar el archivo, y que este no se ejecute al instante } }
private void AddMetaData(Document document) { document.AddCreationDate(); document.AddAuthor("DYNATEC AS"); document.AddCreator("EasyDOC 1.0"); //TODO: set language document.AddLanguage(_doc.Language.Name); document.AddTitle(Documentation.Name); }
private static void Author(Document pdfFile, Enum authorName, string title) { pdfFile.AddCreator(authorName.ToString()); //Oluşturan kişinin isminin eklenmesi pdfFile.AddCreationDate(); //Oluşturulma tarihinin eklenmesi pdfFile.AddAuthor(authorName.ToString()); //Yazarın isiminin eklenmesi pdfFile.AddHeader("Başlık", "Sürücü Kursu Otomasyonu"); pdfFile.AddTitle(title); //Başlık ve title eklenmesi }
private void To_pdf(string paciente, string doctor, string fecha, string diagnostico, string tratamiento, string medicamento) { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=print.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 10f); HTMLWorker htmlParser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); string remito = "Autorizo: OSVALDO SANTIAGO ESTRADA"; string envio = "Fecha:" + DateTime.Now.ToString(); Chunk chunk = new Chunk("INFORME DE ATENCION", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD)); pdfDoc.Add(new Paragraph(chunk)); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph("------------------------------------------------------------------------------------------")); pdfDoc.Add(new Paragraph("Paciente: " + paciente)); pdfDoc.Add(new Paragraph("Doctor: " + doctor)); pdfDoc.Add(new Paragraph("Fecha Atención: " + fecha)); pdfDoc.Add(new Paragraph("------------------------------------------------------------------------------------------")); pdfDoc.Add(new Paragraph("DIAGNOSTICO ", FontFactory.GetFont("ARIAL", 16, iTextSharp.text.Font.BOLD))); pdfDoc.Add(new Paragraph(diagnostico)); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph("------------------------------------------------------------------------------------------")); pdfDoc.Add(new Paragraph("TRATAMIENTO ", FontFactory.GetFont("ARIAL", 16, iTextSharp.text.Font.BOLD))); pdfDoc.Add(new Paragraph(tratamiento)); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph("------------------------------------------------------------------------------------------")); pdfDoc.Add(new Paragraph("MEDICAMENTO ", FontFactory.GetFont("ARIAL", 16, iTextSharp.text.Font.BOLD))); pdfDoc.Add(new Paragraph(medicamento)); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph("------------------------------------------------------------------------------------------")); pdfDoc.AddCreationDate(); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph(" ")); pdfDoc.Add(new Paragraph("_______________________", FontFactory.GetFont("ARIAL", 16, iTextSharp.text.Font.BOLD))); pdfDoc.Add(new Paragraph("Firma", FontFactory.GetFont("ARIAL", 16, iTextSharp.text.Font.BOLD))); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); }
public ReportPdf(Stream Output, Layout Layout, Template Template, Dictionary <string, string> ConfigParams) : base(Output, Layout, Template, ConfigParams) { Rectangle pageSize = new Rectangle(mm2pt(Template.PageSize.Width), mm2pt(Template.PageSize.Height)); // Initialization m_Document = new Document(pageSize, mm2pt(Template.Margin.Left), mm2pt(Template.Margin.Right), mm2pt(Template.Margin.Top), mm2pt(Template.Margin.Bottom)); m_Writer = PdfWriter.GetInstance(m_Document, Output); m_Document.AddCreationDate(); m_Document.AddCreator("StrengthReport http://dev.progterv.info/strengthreport) and KeePass (http://keepass.info)"); m_Document.AddKeywords("report"); m_Document.AddTitle(Layout.Title + " (report)"); // Header HeaderFooter header = new HeaderFooter(new Phrase(Layout.Title + ", " + DateTime.Now.ToString(), m_Template.ReportFooter.getFont()), false); header.Alignment = Template.ReportFooter.getAlignment(); m_Document.Header = header; // Footer HeaderFooter footer = new HeaderFooter(new Phrase(new Chunk("Page ", m_Template.ReportFooter.getFont())), new Phrase(new Chunk(".", m_Template.ReportFooter.getFont()))); footer.Alignment = Template.ReportFooter.getAlignment(); m_Document.Footer = footer; // TODO: Metadata // Open document m_Document.Open(); // Report Heading { PdfPTable reportTitle = new PdfPTable(1); PdfPCell titleCell = new PdfPCell(new Phrase(Layout.Title, m_Template.ReportHeader.getFont())); titleCell.Border = 0; titleCell.FixedHeight = mm2pt(m_Template.ReportHeader.Height); titleCell.VerticalAlignment = Element.ALIGN_MIDDLE; titleCell.HorizontalAlignment = m_Template.ReportHeader.getAlignment(); reportTitle.AddCell(titleCell); reportTitle.WidthPercentage = 100; m_Document.Add(reportTitle); } // Create main table m_Table = new PdfPTable(Layout.GetColumnWidths()); m_Table.WidthPercentage = 100; m_Table.HeaderRows = 1; foreach (LayoutElement element in Layout) { PdfPCell cell = new PdfPCell(new Phrase(element.Title, m_Template.Header.getFont())); cell.BackgroundColor = m_Template.Header.Background.ToColor(); cell.MinimumHeight = mm2pt(m_Template.Header.Height); cell.VerticalAlignment = Element.ALIGN_MIDDLE; m_Table.AddCell(cell); } m_colorRow = new CMYKColor[] { m_Template.Row.BackgroundA.ToColor(), m_Template.Row.BackgroundB.ToColor() }; }
public void ExtrairTextoPDF(string caminho) { List <String> Holerites = new List <string>(); using (PdfReader pdf = new PdfReader(caminho + "Holerites - Modelo.pdf")) { for (int numeroPagina = 1; numeroPagina <= pdf.NumberOfPages; numeroPagina++) { var conteudoDaPagina = pdf.GetPageContent(numeroPagina); var pagina = PdfTextExtractor.GetTextFromPage(pdf, numeroPagina); var ocorrenciaAtual = 1; var tentativas = 1; String linhaDoNome = null; while (tentativas != 6) { if (tentativas > 1) { ocorrenciaAtual = pagina.IndexOf("\n", ocorrenciaAtual + 2); } else { ocorrenciaAtual = pagina.IndexOf("\n", ocorrenciaAtual); } var stringAtual = pagina.Substring(ocorrenciaAtual, pagina.IndexOf("\n", ocorrenciaAtual + 2)); tentativas++; linhaDoNome = stringAtual; } var index = linhaDoNome.IndexOf("\n", 2); linhaDoNome = linhaDoNome.Substring(1, index - 2); Regex regex = new Regex("[0-9]"); String nome = regex.Replace(linhaDoNome, "").TrimEnd().TrimStart(); Holerites.Add(pagina); Document doc = new Document(PageSize.A4); doc.AddCreationDate(); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream($"{caminho}Holerites.{nome.Trim()}.pdf", FileMode.Create)); doc.Open(); doc.Add(new Paragraph(" ")); doc.Close(); using (var stream = new FileStream($"{caminho}Holerites.{nome.Trim()}.pdf", FileMode.Append)) { stream.Write(conteudoDaPagina, 0, conteudoDaPagina.Length); } } } }
private MemoryStream RunPL(string strm, string class_nbr) { Document document = new Document(PageSize.A4); document.SetMargins(40, 40, 40, 80); document.AddCreationDate(); MemoryStream output = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, output); try { document.Open(); string textData = ""; Paragraph elements; elements = new Paragraph(textData, new Font(Font.NORMAL, 14)); elements.Alignment = Element.ALIGN_CENTER; elements.Add("Lista de presença\n"); document.Add(elements); elements = new Paragraph(textData, new Font(Font.NORMAL, 12)); elements.Alignment = Element.ALIGN_LEFT; string query = "SELECT b.descr, a.descr from class_tbl a INNER JOIN term_tbl b ON b.strm = a.strm WHERE a.strm = '" + strm + "' AND a.class_nbr = '" + class_nbr + "'"; List <Object[]> result = database.ExecuteQuery(query); elements.Add("\nPeríodo Letivo: " + result[0][0] + "\nAula: " + result[0][1] + "\n\n"); document.Add(elements); query = "SELECT b.name_display from stdnt_enrl a INNER JOIN personal_data b ON b.student_id = a.student_id WHERE a.strm = '" + strm + "' AND a.class_nbr = '" + class_nbr + "'"; result = database.ExecuteQuery(query); PdfPTable table = new PdfPTable(2); table.HorizontalAlignment = Element.ALIGN_LEFT; Font tableFont = new Font(Font.NORMAL, 8); foreach (Object[] student in result) { table.AddCell(new PdfPCell(new Phrase((string)student[0], tableFont)) { Border = Rectangle.NO_BORDER }); table.AddCell(new PdfPCell(new Phrase("______________________________________\n", tableFont)) { Border = Rectangle.NO_BORDER }); } document.Add(table); } finally { document.Close(); } return(output); }
private static void AddMetadata() { document.AddAuthor(ConfigurationManager.AppSettings["autor"].ToString()); document.AddCreator(Assembly.GetEntryAssembly().GetName().Version.ToString()); document.AddKeywords(ConfigurationManager.AppSettings["palavrasChave"].ToString()); document.AddCreationDate(); document.AddTitle(ConfigurationManager.AppSettings["titulo"].ToString()); document.AddSubject(ConfigurationManager.AppSettings["assunto"].ToString()); }