Foros del Web » Programación para mayores de 30 ;) » .NET »

[Aporte] Crear PDF usando PDFsharp, VBScript

Estas en el tema de [Aporte] Crear PDF usando PDFsharp, VBScript en el foro de .NET en Foros del Web. Hola a todos, a continuuacion he utilizado mis conocimientos de VB para traducir y utilizar la libreria PDFsharp en paginas web al vuelo (on the ...
  #1 (permalink)  
Antiguo 16/07/2010, 21:27
Avatar de gakutaru  
Fecha de Ingreso: agosto-2005
Ubicación: frente a mi NtbK
Mensajes: 239
Antigüedad: 18 años, 7 meses
Puntos: 6
[Aporte] Crear PDF usando PDFsharp, VBScript

Hola a todos, a continuuacion he utilizado mis conocimientos de VB para traducir y utilizar la libreria PDFsharp en paginas web al vuelo (on the fly).

Es un unico ejemplo que incluye todo lo que permite utilizarce desde la Web,
algo que no pude solucionar fue el insertarle imagenes al PDF.
pues me devuelve el error: BC30652: Es necesaria una referencia al ensamblado 'WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' que contiene el tipo 'System.Windows.Point'. Agregue una al proyecto.
y desconosco la solucion.
si alguien lo soluciona, se agradece que lo reporte.

sin mas, el codigo: (en dos partes pues es muy largo el codigo, pero es un unico archivo y entre ingles y español xq somos bilingues a lo spanglish )

Default.aspx
Código:
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="PdfSharp" %>
<%@ Import Namespace="PdfSharp.Pdf" %>
<%@ Import Namespace="PdfSharp.Drawing" %>
<%@ Import Namespace="PdfSharp.Drawing.Layout" %>

<html>
<head runat="server">
<title>Gabriel Diaz</title>
<script runat="server">
    Sub Page_Load()
        ' Create a new PDF document
        Dim document As PdfDocument = New PdfDocument
        document.Info.Title = "Created with PDFsharp"
        document.Info.Author = "Stefan Lange"
        document.Info.Subject = "traducido a vbscript por Gabriel Diaz"
        ' Create an empty page
        Dim page As PdfPage = document.AddPage
 
        ' Get an XGraphics object for drawing
        Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
 
        ' Draw an ellipse
        Dim pen As XPen = New XPen(XColor.FromArgb(255, 0, 0))
        gfx.DrawEllipse(pen, 3 * page.Width.Point / 10, 3 * page.Height.Point / 10, 2 * page.Width.Point / 5, 2 * page.Height.Point / 5)
 
        'Draw an arc
        Dim pen2 As New XPen(XColors.Red, 1)
        gfx.DrawArc(pen2, 300, 5, 100, 100, 300, 360) 'pen2, x, y , largo x, largo y, ??, grados que son cubiertos
      
        'draw an rectabgle
        Dim pen3 As New XPen(XColors.Navy, Math.PI)
        gfx.DrawRectangle(pen3, 10, 0, 100, 60)
        gfx.DrawRectangle(XBrushes.DarkOrange, 130, 0, 100, 60)
        gfx.DrawRectangle(pen3, XBrushes.DarkOrange, 10, 80, 100, 60)
        gfx.DrawRectangle(pen3, XBrushes.DarkOrange, 150, 80, 60, 60)
        
        'Draw pies
        Dim pen4 As New XPen(XColors.DarkBlue, 2.5)
        gfx.DrawPie(pen4, 10, 160, 100, 90, -120, 75)
        gfx.DrawPie(XBrushes.Gold, 130, 160, 100, 90, -160, 150)
        gfx.DrawPie(pen4, XBrushes.Gold, 10, 210, 100, 90, 80, 70)
        gfx.DrawPie(pen4, XBrushes.Gold, 150, 240, 60, 60, 35, 290)
        
        'Draw text in different styles
        Const facename As String = "Times New Roman"

        Dim options As New XPdfFontOptions(PdfFontEncoding.WinAnsi, PdfFontEmbedding.[Default])

        Dim fontRegular As New XFont(facename, 10, XFontStyle.Regular, options)
        Dim fontBold As New XFont(facename, 15, XFontStyle.Bold, options)
        Dim fontItalic As New XFont(facename, 20, XFontStyle.Italic, options)
        Dim fontBoldItalic As New XFont(facename, 25, XFontStyle.BoldItalic, options)

        ' The default alignment is baseline left (that differs from GDI+)
        gfx.DrawString("Times (regular, font 10)", fontRegular, XBrushes.DarkSlateGray, 400, 30)
        gfx.DrawString("Times (bold, font 15)", fontBold, XBrushes.DarkSlateGray, 400, 65)
        gfx.DrawString("Times (italic, font 20)", fontItalic, XBrushes.DarkSlateGray, 400, 100)
        gfx.DrawString("Times (bold italic, font 25)", fontBoldItalic, XBrushes.DarkSlateGray, 400, 135)
        
        
        ' Create a font
        Dim font As XFont = New XFont("Verdana", 20, XFontStyle.Bold)
 
        ' Draw the text
        gfx.DrawString("Hola, Mundo!", font, XBrushes.Black, New XRect(0, 0, page.Width.Point, page.Height.Point), XStringFormats.Center)
      
        
        'pagina nueva
        Dim page2 As PdfPage = document.AddPage
        Dim gfx2 As XGraphics = XGraphics.FromPdfPage(page2)
        
        'Show how to align text in the layout rectangle
        Dim rect As New XRect(10, 10, 250, 140)

        Dim font2 As New XFont("Verdana", 10)
        Dim brush As XBrush = XBrushes.Red
        Dim format As New XStringFormat()

        gfx2.DrawRectangle(XPens.YellowGreen, rect)
     
        gfx2.DrawString("TopLeft", font2, brush, rect, format)

        format.Alignment = XStringAlignment.Center
        gfx2.DrawString("TopCenter", font2, brush, rect, format)

        format.Alignment = XStringAlignment.Far
        gfx2.DrawString("TopRight", font2, brush, rect, format)


        format.LineAlignment = XLineAlignment.Center
        format.Alignment = XStringAlignment.Near
        gfx2.DrawString("CenterLeft", font2, brush, rect, format)

        format.Alignment = XStringAlignment.Center
        gfx2.DrawString("Center", font2, brush, rect, format)

        format.Alignment = XStringAlignment.Far
        gfx2.DrawString("CenterRight", font2, brush, rect, format)

        format.LineAlignment = XLineAlignment.Far
        format.Alignment = XStringAlignment.Near
        gfx2.DrawString("BottomLeft", font2, brush, rect, format)

        format.Alignment = XStringAlignment.Center
        gfx2.DrawString("BottomCenter", font2, brush, rect, format)

        format.Alignment = XStringAlignment.Far
        gfx2.DrawString("BottomRight", font2, brush, rect, format)

Última edición por gakutaru; 16/07/2010 a las 22:06
  #2 (permalink)  
Antiguo 16/07/2010, 21:27
Avatar de gakutaru  
Fecha de Ingreso: agosto-2005
Ubicación: frente a mi NtbK
Mensajes: 239
Antigüedad: 18 años, 7 meses
Puntos: 6
Respuesta: [Aporte] Crear PDF usando PDFsharp, VBScript

Código:
                
        'Show how to get text metric information
        Const style As XFontStyle = XFontStyle.Regular
        Dim font3 As New XFont("Times New Roman", 95, style)

        Const text As String = "Desert"
        Const x As Double = 300, y As Double = 100 'posicion del texto
        Dim size As XSize = gfx.MeasureString(text, font3)

        Dim lineSpace As Double = font3.GetHeight(gfx)
        Dim cellSpace As Integer = font3.FontFamily.GetLineSpacing(style)
        Dim cellAscent As Integer = font3.FontFamily.GetCellAscent(style)
        Dim cellDescent As Integer = font3.FontFamily.GetCellDescent(style)
        Dim cellLeading As Integer = cellSpace - cellAscent - cellDescent

        ' Get effective ascent
        Dim ascent As Double = lineSpace * cellAscent / cellSpace
        gfx2.DrawRectangle(XBrushes.Bisque, x, y - ascent, size.Width, ascent)

        ' Get effective descent
        Dim descent As Double = lineSpace * cellDescent / cellSpace
        gfx2.DrawRectangle(XBrushes.LightGreen, x, y, size.Width, descent)

        ' Get effective leading
        Dim leading As Double = lineSpace * cellLeading / cellSpace
        gfx2.DrawRectangle(XBrushes.Yellow, x, y + descent, size.Width, leading)


        ' Draw text half transparent
        Dim color As XColor = XColors.DarkSlateBlue
        color.A = 1.2
        gfx2.DrawString(text, font3, New XSolidBrush(color), x, y)
        
        'ingresar textos
       Dim text2 As String = "El latín es una lengua de la rama itálica que fue hablada en la antigua"
        text2 &= " República Romana y el Imperio romano desde el siglo IX a. C. "
        text2 &= "Su nombre deriva de la existencia de una zona geográfica de la península itálica"
        text2 &= " denominada Vetus Latium o 'Antiguo llano' (hoy llamado Lacio)."
        text2 &= "Ganó gran importancia con la expansión del estado romano, siendo lengua oficial del imperio"
        text2 &= " en gran parte de Europa y África septentrional, junto con el griego. Como las demás lenguas indoeuropeas en general, "
        text2 &= " el latín era una lengua flexiva de tipo fusional con un mayor grado de síntesis nominal que las actuales lenguas romances,"
        text2 &= " en la cual dominaba la flexión mediante sufijos, combinada en determinadas veces con el"
        text2 &= "uso de las preposiciones; mientras que en las lenguas modernas derivadas dominan las construcciones analíticas con preposiciones, habiéndose reducido"
        text2 &= "la flexión nominal a marcar sólo el género y el plural, conservando los casos de declinación"
        text2 &= " sólo en los pronombres personales (teniendo estos un orden fijo en los sintagmas verbales).1"

        Dim tf As New XTextFormatter(gfx2)

        Dim rect2 As New XRect(40, 200, 250, 220)
        font = New XFont("Times New Roman", 10, XFontStyle.Bold)
        gfx2.DrawRectangle(XBrushes.SeaShell, rect)
        'tf.Alignment = ParagraphAlignment.Left
        tf.DrawString(text2, font, XBrushes.Black, rect2, XStringFormats.TopLeft)

        rect2 = New XRect(310, 200, 250, 220)
        gfx2.DrawRectangle(XBrushes.SeaShell, rect)
        tf.Alignment = XParagraphAlignment.Right
        tf.DrawString(text2, font, XBrushes.Black, rect2, XStringFormats.TopLeft)

        rect2 = New XRect(40, 500, 250, 220)
        gfx2.DrawRectangle(XBrushes.SeaShell, rect)
        tf.Alignment = XParagraphAlignment.Center
        tf.DrawString(text2, font, XBrushes.Black, rect2, XStringFormats.TopLeft)

        rect2 = New XRect(310, 500, 250, 220)
        gfx2.DrawRectangle(XBrushes.SeaShell, rect)
        tf.Alignment = XParagraphAlignment.Justify
        tf.DrawString(text2, font, XBrushes.Black, rect2, XStringFormats.TopLeft)
 
        'pie de pagina
        Dim rect3 As New XRect(New XPoint(), gfx.PageSize)
        rect3.Inflate(-10, -15)
        Dim font4 As New XFont("Verdana", 14, XFontStyle.Bold)
        gfx.DrawString(Title, font4, XBrushes.MidnightBlue, rect3, XStringFormats.TopCenter)

        rect3.Offset(0, 5)
        font4 = New XFont("Verdana", 8, XFontStyle.Italic)
        Dim format2 As New XStringFormat()
        format2.Alignment = XStringAlignment.Near
        format2.LineAlignment = XLineAlignment.Far
        gfx.DrawString("creado por " & PdfSharp.ProductVersionInfo.Producer, font4, XBrushes.Blue, rect3, format2)
        gfx2.DrawString("creado por " & PdfSharp.ProductVersionInfo.Producer, font4, XBrushes.Blue, rect3, format2)
       
        font4 = New XFont("Verdana", 8)
        format2.Alignment = XStringAlignment.Center
        gfx.DrawString(document.PageCount.ToString(), font4, XBrushes.DarkOrchid, rect3, format2)
        gfx2.DrawString(document.PageCount.ToString(), font4, XBrushes.DarkOrchid, rect3, format2)
       
        document.Outlines.Add(Title, page, True)
        
        ' guardar el documento en un directorio especifico
        'Dim filename As String = "C:\Inetpub\wwwroot\PDF\funciona1\HelloWorld.pdf"
        ' document.Save(filename)
        
        ' mostrar el pdf en el explorador
        Dim stream As New MemoryStream()
        document.Save(stream, False)
        Response.Clear()
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-length", stream.Length.ToString())
        Response.BinaryWrite(stream.ToArray())
        Response.Flush()
        stream.Close()
        Response.[End]()
 
    
    End Sub
</script>
</head>
<body>
</body>
</html>
Algunos errores...

necesitan tener la libreria, pueden descargarla de la pagina del autor, el archivo de nombre: "PdfSharp-WPF.dll" y recuerden ubicarla en su directorio BIN, recuerden que si es directorio virtual la carpeta BIN va en la raiz del servidor
(.../wwwroot/BIN/PdfSharp-WPF.dll)

pueden descargar el archivo adjunto, que incluye el ejemplo con todo lo que se puede utilizar y la libreria PDFsharp hasta esta fecha (16-julio del 2010)
http://www.megaupload.com/?d=O3D72B59

Última edición por gakutaru; 16/07/2010 a las 22:05

Etiquetas: aspx, crear, pdf, pdfsharp, vbscript
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:20.