Foros aprenderaprogramar.com
Aprender a programar => Aprender a programar desde cero => Mensaje iniciado por: Mary en 02 de Agosto 2016, 20:21
-
Hola a tod@s, estoy intentado hacer un informe en .pdf con un texto que introduzco a través de un Richtextbox usando la biblioteca iTextSharp. El problema es que no consigo que el texto pase a la hoja .pdf con el mismo formato (fuente, tamaño, negrita etc.) con el que lo he escrito dentro del Richtextbox.
Por el momento el código que tengo es el siguiente:
Dim document As New Document(PageSize.A4, 65, 65, 200, 80)
Dim filename22 As String = Environment.GetFolderPath__(Environment.SpecialFolder.DesktopDirectory) + "\Report.pdf"
Dim file As New FileStream(filename22, FileMode.Create, FileAccess.Write,_ _FileShare.ReadWrite)
Dim fuente As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN,_ _BaseFont.CP1252, False)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, file)
document.Open()
document.NewPage()
document.Add(New iTextSharp.text.Paragraph(RichTextBox1.Text))
document.Close()
Process.Start(filename22)
writer.Close()
¿Alguien sabría como conseguir que copie el texto con el mismo formato? Además también necesito que lo inserte en el documento .pdf con la alineación justificada, tal y como se hace en los documentos de Word. Esto lo he estado buscando en la web, pero hasta el momento no consigo que funcione nada de lo que he encontrado.
Gracias y saludos.
Lo siento pero he escribo el código de este modo, porque no consigo que me funcione la opción de Insertar código.
-
Hola!
Para ver cómo insertar código lee las instrucciones en https://www.aprenderaprogramar.com/foros/index.php?topic=1460.0
También es importante que indiques en qué lenguaje estás trabajando (e incluso la versión), qué bibliotecas estás usando, etc.
He visto este ejemplo para trasladar el contenido de un richtextbox a un pdf usando la biblioteca iTextSharp
// step 1: creation of a document-object
iTextSharp.text.Document myDocument = new iTextSharp.text.Document(PageSize.A4.Rotate());
try
{
// step 2:
// Now create a writer that listens to this doucment and writes the document to desired Stream.
PdfWriter.GetInstance(myDocument, new FileStream(sfd.FileName, FileMode.Create));
// step 3: Open the document now using
myDocument.Open();
// step 4: Now add some contents to the document
myDocument.Add(new iTextSharp.text.Paragraph(richTextBox1.Text));
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// step 5: Remember to close the documnet
myDocument.Close();
Pero no estoy seguro de que esto te vaya a exportar los estilos desde el richTextBox al pdf (por ejemplo la alineación justificada). Como opción alternativa está convertir el código rtf del RichTextBox a HTML, y luego usar XMLWorkerHelper para generar el pdf. En ese caso hacen falta las dll:
itextsharp.dll
itextsharp.xmlworker.dll
Saludos!
-
Hola,
Lo siento, ya es la segunda vez que me pasa. Trabajo con lenguaje visual basic y con Visual Basic Studio 2010 express.
Gracias por la alternativa que me has pasado, pero ya lo había intentado y no he conseguido que funcione.
En cuanto a la segunda alternativa que me has dado, ¿podrías especificar un poco más como se podría hacer? como se puede pasar de rtf a HTML en Visual Basic? Gracias.
Saludos.
-
Buenas puedes probar añadiendo esta función a tu proyecto; para que funcione debes añadir una referencia a la librería Microsoft Word 12.0 Object Library (COM object). Los comentarios van explicando los pasos (en inglés)
Public Function sRTF_To_HTML(ByVal sRTF As String) As String
'Declare a Word Application Object and a Word WdSaveOptions object
Dim MyWord As Microsoft.Office.Interop.Word.Application
Dim oDoNotSaveChanges As Object = _
Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges
'Declare two strings to handle the data
Dim sReturnString As String = ""
Dim sConvertedString As String = ""
Try
'Instantiate the Word application,
‘set visible to false and create a document
MyWord = CreateObject("Word.application")
MyWord.Visible = False
MyWord.Documents.Add()
'Create a DataObject to hold the Rich Text
'and copy it to the clipboard
Dim doRTF As New System.Windows.Forms.DataObject
doRTF.SetData("Rich Text Format", sRTF)
Clipboard.SetDataObject(doRTF)
'Paste the contents of the clipboard to the empty,
'hidden Word Document
MyWord.Windows(1).Selection.Paste()
'…then, select the entire contents of the document
'and copy back to the clipboard
MyWord.Windows(1).Selection.WholeStory()
MyWord.Windows(1).Selection.Copy()
'Now retrieve the HTML property of the DataObject
'stored on the clipboard
sConvertedString = _
Clipboard.GetData(System.Windows.Forms.DataFormats.Html)
'Remove some leading text that shows up in some instances
'(like when you insert it into an email in Outlook
sConvertedString = _
sConvertedString.Substring(sConvertedString.IndexOf("<html"))
'Also remove multiple  characters that somehow end up in there
sConvertedString = sConvertedString.Replace("Â", "")
'…and you're done.
sReturnString = sConvertedString
If Not MyWord Is Nothing Then
MyWord.Quit(oDoNotSaveChanges)
MyWord = Nothing
End If
Catch ex As Exception
If Not MyWord Is Nothing Then
MyWord.Quit(oDoNotSaveChanges)
MyWord = Nothing
End If
MsgBox("Error converting Rich Text to HTML")
End Try
Return sReturnString
End Function
'
'That does it. If you need to insert your HTML into an
'Outlook mail message (as I did) here's how to do it using the function above.
'
Dim myotl As Microsoft.Office.Interop.Outlook.Application
Dim myMItem As Microsoft.Office.Interop.Outlook.MailItem
myotl = CreateObject("Outlook.application")
myMItem = myotl.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
myMItem.Subject =
"This email was converted from rich text to HTML using a simple function in VB.net"
myMItem.Display(False)
myMItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML
myMItem.HTMLBody = sConvertedString
Salu2
-
Hola de nuevo,
gracias por la función. La probé y transforma el texto que pongo en el richtextbox1 en código html en el richtextbox2.
Ahora lo que he estoy intentando y no hay forma de conseguir es pasar el texto html del richtextbox2 a un documento pdf.
He buscando por la web formas de hacerlo pero todas las que he probado no han funcionado ya que siempre me salta un error y no se genera el documento.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
RichTextBox2.Text = sRTF_To_HTML(RichTextBox1.Text)
Dim htmlReport As String = RichTextBox2.ToString
'Dim filename22 As String = Path.Combine(Server.MapPath("~/PDF"), "test.pdf")
Dim filename22 As String = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + ("\Report1.pdf")
'Convert to pdf
Dim document As New Document(iTextSharp.text.PageSize.A4.Rotate(), 1, 1, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream(filename22, FileMode.Create))
document.Open()
' document.NewPage()
Dim worker As XMLWorkerHelper = XMLWorkerHelper.GetInstance
worker.ParseXHtml(writer, document, New StringReader(htmlReport))
document.Close()
End Sub
En el form hay dos Richtextbox y un Button. En el Richtextbox1 escribo un texto, cuando pulso el Button, gracias a la función sRTF_To_HTML el texto del Richtextbox1 se transforma en formato HTML en el Richtextbox2 pero no hay forma de conseguir que se transforme en .pdf. Me salta el siguiente error "El documento no tiene páginas".
Si añado la línea Document.add(worker) me salta el error "No se puede convertir un objeto de tipo 'iTextSharp.tool.xml.XMLWorkerHelper' al tipo 'iTextSharp.text.IElement'".
Alguien sabría alguna solución a este problema? Ya no tengo ni idea de como poder solucionarlo.
Gracias y saludos.
-
Buenas códigos que pueden servir de idea para probar
Dim file As String = "C:\ALMACENCFD\Documento.pdf"
Dim html As String = System.IO.File.ReadAllText("C:\ALMACENCFD\temp.txt")
Dim document As New Document(PageSize.A4, 15, 20, 15, 25)
PdfWriter.GetInstance(document, New FileStream(file, FileMode.Create))
document.Open()
For Each E1 As IElement In HTMLWorker.ParseToList(New StringReader(html), New StyleSheet())
document.Add(E1)
Next
document.Close()
También
Dim htmlReport As String = output.ToString
'Convert to pdf
Dim document As New Document(iTextSharp.text.PageSize.A4.Rotate(), 1, 1, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(Document, New FileStream(Request.PhysicalApplicationPath + "\Export\test.pdf", FileMode.Create))
document.Open()
Dim worker As XMLWorkerHelper = XMLWorkerHelper.GetInstance
worker.ParseXHtml(writer, document, New StringReader(htmlReport))
Un problema que se suele comentar que aparece con frecuencia es no tener las mismas versiones de los dll, itextsharp.dll y itextsharp.xmlworker.dll hay que asegurarse que estos archivos dll estén actualizados
Salu2