iTextSharp的问题.将excel转换为pdf [英] Problems with iTextSharp. Convert excel to pdf

查看:81
本文介绍了iTextSharp的问题.将excel转换为pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我是新编程人员,请帮忙.

我从互联网上得到一个例子,显然可以很好地将excel文档转换为pdf.

但是,当我打开Pdf文档而不是相同的信息时,会出现不同种类的字符(类似于加密学),这显然与电子表格不同.

谁能帮我吗?.

代码:::

Hi guys!!

I''m new programming and i need some help, please.

I got an example from internet that apparently work quite well converting excel document to pdf.

But when I open the Pdf document instead of the same information, appears a differents kinds of characters (something like encryptology) that obviously aren''t the same from the spreadsheet.

Can anyone help me??.

The Code:::

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
//importamos 
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iTextSharp_bigpercynet
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnGenerarPDF;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnGenerarPDF = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// btnGenerarPDF
			// 
			this.btnGenerarPDF.Location = new System.Drawing.Point(24, 16);
			this.btnGenerarPDF.Name = "btnGenerarPDF";
			this.btnGenerarPDF.Size = new System.Drawing.Size(184, 24);
			this.btnGenerarPDF.TabIndex = 0;
			this.btnGenerarPDF.Text = "&Generar PDF";
			this.btnGenerarPDF.Click += new System.EventHandler(this.btnGenerarPDF_Click);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(248, 70);
			this.Controls.Add(this.btnGenerarPDF);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
			this.Name = "Form1";
			this.Text = "trabajando con iTextSharp";
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void btnGenerarPDF_Click(object sender, System.EventArgs e)
		{
			//creamos el documento
            //...ahora configuramos para que el tamaño de hoja sea A4
			Document document = new Document(iTextSharp.text.PageSize.A4); 
			document.PageSize.BackgroundColor= new iTextSharp.text.Color(255, 255,255);
			//document.PageSize.Rotate();
			
			//...definimos el autor del documento.
			//document.AddAuthor("Arbis Percy Reyes Paredes");

			//...el creador, que será el mismo eh!
			//document.AddCreator("Arbis Percy Reyes Paredes");

			//hacemos que se inserte la fecha de creación para el documento
			//document.AddCreationDate();
			//...título

			//document.AddTitle("Generación de un pdf con itextSharp");
			//... el asunto

            //document.AddSubject("Este es un paso muy important");
			//... palabras claves

			//document.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");

			//creamos un instancia del objeto escritor de documento
			PdfWriter writer = PdfWriter.GetInstance(document,new System.IO.FileStream
				("Code.pdf", System.IO.FileMode.Create));
			

			//encriptamos el pdf, dándole como clave de usuario "key" y la clave del dueño será "owner"
			//si quitas los comentarios (en writer.SetEncryption...), entonces el documento generado
			//no mostrarà tanto la información de autor, titulo, fecha de creacion... 
			//que habiamos establecio más arriba. y sólo podrás abrirlo con una clave

			//writer.SetEncryption(PdfWriter.STRENGTH40BITS,"key","owner", PdfWriter.CenterWindow);
			
			//definimos la manera de inicialización de abierto del documento.
			//esto, hará que veamos al inicio, todas la páginas del documento
			//en la parte izquierda
			writer.ViewerPreferences= PdfWriter.PageModeUseThumbs;

								
            //con esto conseguiremos que el documento sea presentada de dos en dos 
			writer.ViewerPreferences=PdfWriter.PageLayoutTwoColumnLeft;

			//con esto podemos oculta las barras de herramienta y de menú respectivamente.
			//(quite las dos barras de comentario de la siguiente línea para ver los efectos)
			//PdfWriter.HideToolbar | PdfWriter.HideMenubar
  
			//abrimos el documento para agregarle contenido
			document.Open();

			//este stream es para jalar el código
			string TemPath=Application.StartupPath.ToString();
			TemPath=TemPath.Substring(0,TemPath.Length -10);
			string pathFileForm1cs=TemPath + @"\excel.xls";
			System.IO.StreamReader reader = new System.IO.StreamReader(pathFileForm1cs);

			//leemos primera línea
			string linea= reader.ReadLine();

			//creamos la fuente
			iTextSharp.text.Font myfont= new iTextSharp.text.Font(
				FontFactory.GetFont(FontFactory.COURIER, 10, iTextSharp.text.Font.ITALIC));

			//creamos un objeto párrafo, donde insertamos cada una de las líneas que 
			//se vaya leyendo mediante el reader 
			Paragraph myParagraph = new Paragraph("Código fuente en Visual C# \n\n",myfont);
			
			do
			{
				//leyendo linea de texto
				linea=reader.ReadLine() ;	
				//concatenando cada parrafo que estará formado por una línea
				myParagraph.Add(new Paragraph(linea,myfont));
			}while(linea !=null);  //mientras no llegue al final de documento, sigue leyendo
			
			//agregar todo el paquete de texto
			document.Add(myParagraph);		
	
			//esto es importante, pues si no cerramos el document entonces no se creara el pdf.
			document.Close();

			//esto es para abrir el documento y verlo inmediatamente después de su creación
			System.Diagnostics.Process.Start("AcroRd32.exe","Code.pdf");
							  
		}
	}
}



谢谢.

Edy.



Thanks.

Edy.

推荐答案

您只是逐行读取xls文件并将其传递给itextSharp-这将不起作用,因为您正在读取原始数据而itextSharp并不知道"它是excel-因此它会将您提供的文本写到输出中.

我不认为iTextSharp可以进行转换-它更多是关于从代码中编写PDF文档-我建议您寻找另一个实用程序-但我不知道有任何免费的实用程序可以满足您的要求.

您还可以自动化Excel本身-因为它可以另存为PDF

尝试看一下-可能会有所帮助 [ ^ ]
You are just reading in the xls file line by line and passing it into itextSharp - this won''t work because you are reading in the raw data and itextSharp doesn''t ''know'' it is excel - so it writes the text you give it to the output.

I don''t think iTextSharp allows conversion - it is more about writing PDF documents from your code - I would suggest you look for another utility - but I''m not aware of any free ones that will do what you require.

You could also automate Excel itself - as it can save as PDF

try looking at this - it may help[^]


这篇关于iTextSharp的问题.将excel转换为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆