DEV4 Blog

  • Home
  • /
  • Blog
  • /
  • Generate a simple PDF from a Web Forms application using iTextSharp library

ASP

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="GeneratePdf.aspx.vb" Inherits="SampleApp.GeneratePdf" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>

VB.Net

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Public Class GeneratePdf
    Inherits Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim bytes As Byte()
       
        ' Create a stream that we can write to, in this case a MemoryStream
        Using ms = New MemoryStream()

            ' Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
            Using doc = New Document(PageSize.A4, 20, 20, 20, 20)

                ' Create a writer that's bound to our PDF abstraction and our stream
                Using writer = PdfWriter.GetInstance(doc, ms)

                    Try
                        doc.Open()

                        doc.AddTitle("Simple PDF Report")

                        ' Populate page
                        doc.Add(New Phrase("Hello world!"))

                        doc.NewPage()

                        ' Populate page
                        doc.Add(New Phrase("Hello world, again!"))

                        doc.Close()

                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                End Using
            End Using

            ' Close the MemoryStream, grab all of the active bytes from the stream
            bytes = ms.ToArray()

            ' Download PDF
            'Response.AddHeader("content-disposition", $"attachment;filename=report.pdf;")
            
            Response.AddHeader("content-disposition", "inline;") ' Display PDF
            Response.ContentType = "application/pdf"
            Response.BinaryWrite(bytes)
            Response.[End]()

        End Using

    End Sub

End Class

iTextSharp libraries


Published on 18 Dec 2018

Add new comment...