VB.NET PDF創建器(代碼示例教程)

查克尼思·賓
查克尼思·賓
2018年8月28日
已更新 2024年12月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

此教程將逐步指導您如何在VB.NET中創建和編輯PDF文件。 此技術同樣適用於ASP.NET 網頁應用程式控制台應用程式Windows 服務桌面程式。 我們將使用 VB.NET 建立針對 .NET Framework 4.6.2 或 .NET Core 2 的 PDF 專案。您所需的只是一個 Visual Basic .NET 開發環境,例如 Microsoft Visual Studio Community。

要了解如何將 IronPDF 與C# 一起使用,請參閱本指南

要了解如何使用IronPDF與F#,請參閱此指南


概述

使用 IronPDF 建立和編輯 PDF 的 VB .NET 程式碼

使用 VB.NET 將 HTML 渲染成 PDF,應用樣式,利用動態內容,並輕鬆編輯您的文件。 創建 PDF 文件直觀且與 .NET Framework 4.6.2、.NET Core 3.1、.NET 8、7、6 和 5 兼容。無需專有文件格式或調用不同的 API。

此教學提供逐步指引,使用深受開發者喜愛的IronPDF 免費開發軟體完成每項任務。 VB.NET 程式碼範例是針對您的使用案例所設計的,因此您可以在熟悉的環境中輕鬆看到步驟。 這個 VB .NET PDF 函式庫對每個專案都具有全面的創建和設定功能,無論是在 ASP.NET 應用程式、控制檯或桌面上。

隨附於 IronPDF 之內:

  • Ticket support direct from our .NET PDF Library development team (real humans!)
  • Works with HTML, ASPX forms, MVC views, images, and all the document formats you already use
  • Microsoft Visual Studio installation gets you up and running fast
  • Unlimited free development, and licenses to go live starting at $749

    第一步

1. 從IronPDF免費下載VB .NET PDF庫

立即在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer

透過NuGet安裝

在 Visual Studio 中,右鍵單擊您的項目解決方案資源管理器並選擇“管理 NuGet 套件...”。 從那裡開始搜索 IronPDF 並安裝最新版本... 點擊確定以處理彈出的任何對話框。

這適用於任何C# .NET Framework項目,從框架 4.6.2 及以上版本,或.NET Core 2 及以上版本。 它在VB.NET項目中也同樣適用。

Install-Package IronPdf

https://www.nuget.org/packages/IronPdf

透過 DLL 安裝

或者,可以從 https://ironpdf.com/packages/IronPdf.zip 下載 IronPDF DLL 並手動安裝到專案或 GAC。

請記得將此語句添加到使用 IronPDF 的任何 vb 類文件的頂部:


導入 IronPdf;

教學課程

2. 使用 VB.NET 創建 PDF

使用Visual Basic ASP.NET首次創建 PDF 文件時,使用 IronPDF 比起設計專利 API 的庫如 iTextSharp 要容易得多。

我們可以使用 HTML(具有基於 Google Chromium 的像素完美呈現引擎)來定義我們 PDF 的內容,然後簡單地將其呈現到一個檔案中。

以下是我們在 VB.NET 中建立 PDF 的最簡單代碼:

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-1.cs
Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer()
        Dim document = renderer.RenderHtmlAsPdf("<h1> My First PDF in VB.NET</h1>")
        document.SaveAs("MyFirst.pdf")
    End Sub
End Module
VB.NET

這將生成一個.NET生成的PDF文件,其中包含您的確切文本,儘管此時缺少一些設計。

我們可以通過添加標頭行Imports IronPdf來改進此代碼。

透過新增最後一行程式碼System.Diagnostics.Process.Start,我們在作業系統的預設 PDF 檢視器中開啟 PDF,以使專案更具意義。

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-2.cs
Imports IronPdf

Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer()
        Dim document = renderer.RenderHtmlAsPdf("<h1> My First PDF in VB.NET</h1>")
        document.SaveAs("MyFirst.pdf")
        System.Diagnostics.Process.Start("MyFirst.pdf")
    End Sub
End Module
VB.NET

另一種方法是使用IronPDF中的精緻“RenderUrlAsPdf”方法,將任何現有網頁從URL渲染為PDF。

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-3.cs
Imports IronPdf

Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer()
        Dim document = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
        document.SaveAs("UrlToPdf.pdf")
        System.Diagnostics.Process.Start("UrlToPdf.pdf")
    End Sub
End Module
VB.NET

3. 對 VB.NET PDF 應用樣式

要在 VB.NET 中設計我們的 PDF 內容,我們可以充分利用 CSS、JavaScript 和圖像。 我們可能會連結到本地資源,或者連結到遠程或CDN基礎的資源,例如Google Fonts。 我們甚至可以使用DataURIs 將圖像和資源作為字串嵌入到您的 HTML 中

為了進階設計,我們可以使用兩階段程序:

  1. 首先,我们完美地开发和设计我们的HTML。 此任務可能涉及內部設計人員,分擔工作量。

  2. 使用 VB.NET 和我們的 PDF Library 將該文件渲染為 PDF。

    將 HTML 檔案渲染為 PDF 的 VB.NET 程式碼:

    此方法將 HTML 文件呈現為如果它是作為文件(file:// 協議)打開的情況。

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-4.cs
Imports IronPdf

Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer()
        renderer.RenderingOptions.CssMediaType = Rendering.PdfCssMediaType.Print
        renderer.RenderingOptions.PrintHtmlBackgrounds = False
        renderer.RenderingOptions.PaperOrientation = Rendering.PdfPaperOrientation.Landscape
        renderer.RenderingOptions.WaitFor.RenderDelay(150)
        Dim document = renderer.RenderHtmlFileAsPdf("C:\Users\jacob\Dropbox\Visual Studio\Tutorials\VB.Net.Pdf.Tutorial\VB.Net.Pdf.Tutorial\slideshow\index.html")
        document.SaveAs("Html5.pdf")
        System.Diagnostics.Process.Start("Html5.pdf")
    End Sub
End Module
VB.NET

我們也可能通過添加項目相對路徑來縮短該網址,例如:

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-5.cs
Dim document = renderer.RenderHtmlFileAsPdf("..\..\slideshow\index.html")
VB.NET

您可以看到,ChromePdfRenderer 渲染器具有一個RenderingOptions 屬性,我們可以在本範例中使用它來:

  • 將CSS媒體類型設置為「print」,這樣我們就看不到僅限於屏幕的CSS3樣式。
  • 忽略 HTML 背景
  • 將 PDF 的虛擬紙張設定為橫向模式
  • 為了讓 JavaScript 完成處理,添加一個小的渲染延遲。

    我們的範例 HTML 文件使用了 JavaScript、CSS3 和圖片。 此 HTML 創建了一個動態的、適用於移動設備的幻燈片展示,源自於 https://leemark.github.io/better-simple-slideshow/

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-6.cs
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>A simple DIY responsive slideshow made with HTML5, CSS3, and JavaScript</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href='http://fonts.googleapis.com/css?family=Open+Sans|Open+Sans+Condensed:700' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="demo/css/demostyles.css">
        <link rel="stylesheet" href="css/simple-slideshow-styles.css">
    </head>
    <body>
        <!--[if lt IE 8]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        <header>
            <h1>A Better Simple Slideshow</h1>
            <p><span class="desc">A simple DIY responsive JavaScript slideshow.</span> [<a href="https://github.com/leemark/better-simple-slideshow">GitHub<span> repo</span></a>]</p>
        </header>
        <div class="bss-slides num1" tabindex="1" autofocus="autofocus">
            <figure>
              <img src="demo/img/medium.jpg" width="100%" /><figcaption>"Medium" by <a href="https://www.flickr.com/photos/thomashawk/14586158819/">Thomas Hawk</a>.</figcaption>
            </figure>
            <figure>
              <img src="demo/img/colorado.jpg" width="100%" /><figcaption>"Colorado" by <a href="https://www.flickr.com/photos/stuckincustoms/88370744">Trey Ratcliff</a>.</figcaption>
            </figure>
            <figure>
              <img src="demo/img/monte-vista.jpg" width="100%" /><figcaption>"Early Morning at the Monte Vista Wildlife Refuge, Colorado" by <a href="https://www.flickr.com/photos/davesoldano/8572429635">Dave Soldano</a>.</figcaption>
            </figure>
            <figure>
              <img src="demo/img/sunrise.jpg" width="100%" /><figcaption>"Sunrise in Eastern Colorado" by <a href="https://www.flickr.com/photos/35528040@N04/6673031153">Pam Morris</a>.</figcaption>
            </figure>
            <figure>
              <img src="demo/img/colorado-colors.jpg" width="100%" /><figcaption>"colorado colors" by <a href="https://www.flickr.com/photos/cptspock/2857543585">Jasen Miller</a>.</figcaption>
            </figure>
        </div> <!-- // bss-slides -->
<div class="content">
<h2>What is it?</h2>
<p>It's a fairly basic slideshow, written in javascript. This is a dual-purpose project, it's meant to be something you can drop right into your page and use if you so choose, but it's also meant as an example/tutorial script showing how to build a simple DIY slideshow from scratch on your own. <a href="http://themarklee.com/2014/10/05/better-simple-slideshow/">Here is a tutorial/walkthrough</a>.</p>
<h2>Features</h2>
<ul>
    <li>fully responsive</li>
    <li>option for auto-advancing slides, or manually advancing by user</li>
    <li>multiple slideshows per-page</li>
    <li>supports arrow-key navigation</li>
    <li>full-screen toggle using HTML5 fullscreen api</li>
    <li>swipe events supported on touch devices (requires <a href="https://github.com/hammerjs/hammer.js">hammer.js</a>)</li>
    <li>written in vanilla JS--this means no jQuery dependency (much &hearts; for <a href="https://github.com/jquery/jquery">jQuery</a> though!)</li>
</ul>
<h2>Getting Started</h2>
<ol>
<li><p>HTML markup for the slideshow should look basically like this, with a container element wrapping the whole thing (doesn't have to be a <span class="code">&lt;div&gt;</span>) and each slide is a <span class="code">&lt;figure&gt;</span>.</p>
<script src="https://gist.github.com/leemark/83571d9f8f0e3ad853a8.js"></script> </li>
<li>Include the script: <span class="code">js/better-simple-slideshow.min.js</span> or <span class="code">js/better-simple-slideshow.js</span></li>
<li>Include the stylesheet <span class="code">css/simple-slideshow-styles.css</span></li>
<li>Initialize the slideshow:
<script src="https://gist.github.com/leemark/479d4ecc4df38fba500c.js"></script>
</li>
</ol>
<h2>Options</h2>
To customize functionality, create an options object, then pass it into <span class="code">makeBSS()</span> as the second argument, as seen below:
<script src="https://gist.github.com/leemark/c6e0f5c47acb7bf9be16.js"></script>
<h2>Demo/Examples</h2>
    <h3>Example #1 (slideshow at top of this page)</h3>
    <p>HTML markup:</p>
    <script src="https://gist.github.com/leemark/19bafdb1abf8f6b4e147.js"></script>
    <p>JavaScript code:</p>
    <script src="https://gist.github.com/leemark/a09d2726b5bfc92ea68c.js"></script>
    <h3>Example #2 (below)</h3>
        <div class="bss-slides num2" tabindex="2">
           <figure>
              <img src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg" width="100%" /><figcaption>"Snowying" by <a href="http://www.flickr.com/photos/fiddleoak/8511209344/">fiddleoak</a>.</figcaption>
           </figure>
            <figure>
                <img src="http://themarklee.com/wp-content/uploads/2013/12/starlight.jpg" width="100%" /><figcaption>"Starlight" by <a href="http://www.flickr.com/photos/chaoticmind75/10738494123/in/set-72157626146319517">ChaoticMind75</a>.</figcaption>
           </figure>
           <figure>
              <img src="http://themarklee.com/wp-content/uploads/2013/12/snowstorm.jpg" width="100%" /><figcaption>"Snowstorm" by <a href="http://www.flickr.com/photos/tylerbeaulawrence/8539457508/">Beaulawrence</a>.</figcaption>
           </figure>
            <figure>
              <img src="http://themarklee.com/wp-content/uploads/2013/12/misty-winter-afternoon.jpg" width="100%" /><figcaption>"Misty winter afternoon" by <a href="http://www.flickr.com/photos/22746515@N02/5277611659/">Bert Kaufmann</a>.</figcaption>
           </figure>
            <figure>
              <img src="http://themarklee.com/wp-content/uploads/2013/12/good-morning.jpg" width="100%" /><figcaption>"Good Morning!" by <a href="http://www.flickr.com/photos/frank_wuestefeld/4306107546/">Frank Wuestefeld</a>.</figcaption>
           </figure>
        </div> <!-- // bss-slides -->
<p>HTML markup:</p>
<script src="https://gist.github.com/leemark/de90c78cb73673650a5a.js"></script>
<p>JavaScript code:</p>
<script src="https://gist.github.com/leemark/046103061c89cdf07e4a.js"></script>
</div> <!-- // content -->
<footer>Example photos are property of their respective owners, all code is <a href="https://github.com/leemark/better-simple-slideshow/blob/gh-pages/LICENSE">freely licensed for your use</a>. <br>Made especially for you by <a href="http://themarklee.com">Mark Lee</a> aka <a href="http://twitter.com/@therealmarklee">@therealmarklee</a> <br><span>&#9774; + &hearts;</span></footer>
<script src="demo/js/hammer.min.js"></script><!-- for swipe support on touch interfaces -->
<script src="js/better-simple-slideshow.min.js"></script>
<script>
var opts = {
    auto : {
        speed : 3500,
        pauseOnHover : true
    },
    fullScreen : false,
    swipe : true
};
makeBSS('.num1', opts);
var opts2 = {
    auto : false,
    fullScreen : true,
    swipe : true
};
makeBSS('.num2', opts2);
</script>
</body>
</html>
HTML

如您所見,此示例使用了HTML網頁的全部功能。 渲染是由IronPDF內部使用Google的Chromium HTML引擎和v8 JavaScript引擎來執行的。 當您使用 IronPDF 時,整個套件將自動添加到您的項目中,無需在您的系統中安裝。

3.1. 添加頁首和頁尾

既然我們已經有了一個美觀的PDF渲染,我們現在可能希望添加吸引人的頁眉和頁腳。

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-7.cs
Imports IronPdf
Imports IronSoftware.Drawing

Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer()
        renderer.RenderingOptions.CssMediaType = Rendering.PdfCssMediaType.Print
        renderer.RenderingOptions.PrintHtmlBackgrounds = False
        renderer.RenderingOptions.PaperOrientation = Rendering.PdfPaperOrientation.Landscape
        renderer.RenderingOptions.WaitFor.RenderDelay(150)
        renderer.RenderingOptions.TextHeader.CenterText = "VB.NET PDF Slideshow"
        renderer.RenderingOptions.TextHeader.DrawDividerLine = True
        renderer.RenderingOptions.TextHeader.FontSize = "13"
        renderer.RenderingOptions.TextFooter.RightText = "page {page} of {total-pages}"
        renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial
        renderer.RenderingOptions.TextFooter.FontSize = "9"
        Dim document = renderer.RenderHtmlFileAsPdf("..\..\slideshow\index.html")
        document.SaveAs("Html5WithHeader.pdf")
        System.Diagnostics.Process.Start("Html5WithHeader.pdf")
    End Sub
End Module
VB.NET

如所示,支持邏輯頁首和頁腳。 您也可以按照在線VB.NET PDF開發者API參考中描述的方式添加基於HTML的頁眉和頁腳。

您可以下載並探索這個“VB.NET HTML to PDF”項目的源代碼,作為 VB.NET Visual Studio 專案。


4. 創建具有動態內容的PDF:兩種方法

歷史上,對於軟體工程師來說,PDF「範本設計」一直是一項艱鉅的任務。 將內容蓋章到 PDF 模板中很少有效果。 這是因為每個案例或報告都包含不同類型和長度的內容。 幸運地,HTML 在處理動態數據方面表現出色。

對此我們有兩種解決方案:

  1. 使用 .NET 將 HTML 的字串範本轉換成 PDF

  2. 將內容渲染為ASP.NET網頁,然後將該頁面渲染為PDF

4.1 方法 1 - ASP.NET - 使用 VB.NET Web Forms 將 ASPX 转换为 PDF

幸運的是,這個解決方案出奇地簡單。 任何類型的 .NET Web Form(包括 Razor)都可以使用這段 VB.NET 程式碼在 VB.NET 程式碼後端的 Page_Load 子程序中生成為 PDF 文件。

PDF文件可設置內容配置以在瀏覽器中顯示,或作為文件下載使用。

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-8.cs
Imports IronPdf

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim PdfOptions = New IronPdf.ChromePdfRenderOptions()
    IronPdf.AspxToPdf.RenderThisPageAsPDF(AspxToPdf.FileBehavior.Attachment, "MyPdf.pdf", PdfOptions)
End Sub
VB.NET

4.2 方法 2 - 使用字符串模板將HTML轉換為PDF

要創建包含實例特定數據的動態PDF文檔,我們只需創建一個HTML字符串來匹配我們希望渲染為PDF的數據。

這可能是 VB.NET 中 HTML 轉 PDF 解決方案最大的優勢 - 能夠通過即時創建 HTML,輕鬆且直觀地創建動態 PDF 文檔和報告。

這個最簡單的版本是來自 VB.NET 的 String.Format 方法

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-9.cs
Imports IronPdf

Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer()
        Dim Html = "Hello {0}"
        String.Format(Html, "World")
        Dim document = renderer.RenderHtmlAsPdf(Html)
        document.SaveAs("HtmlTemplate.pdf")
        System.Diagnostics.Process.Start("HtmlTemplate.pdf")
    End Sub
End Module
VB.NET

隨著PDF文件變得更加複雜,字符串也會變得更加複雜。 我们可能会考虑使用 String Builder,甚至是像 HandleBars.Net 或 Razor 这样的模板框架。

https://github.com/rexm/Handlebars.Net


5. 使用 VB.NET 編輯 PDF 檔案

IronPDF for VB.NET 也允許PDF文檔被編輯、加密、加水印或甚至轉換回純文本:

5.1. 在VB中合併多個PDF檔案為一個文件

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-10.cs
Dim pdfs = New List(Of PdfDocument)
pdfs.Add(PdfDocument.FromFile("A.pdf"))
pdfs.Add(PdfDocument.FromFile("B.pdf"))
pdfs.Add(PdfDocument.FromFile("C.pdf"))
Dim mergedPdf As PdfDocument = PdfDocument.Merge(pdfs)
mergedPdf.SaveAs("merged.pdf")
mergedPdf.Dispose()
For Each pdf As PdfDocument In pdfs
    pdf.Dispose()
Next
VB.NET

5.2. 向 PDF 添加封面页

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-11.cs
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"))
VB.NET

5.3. 從 PDF 中刪除最後一頁

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-12.cs
pdf.RemovePage((pdf.PageCount - 1))
VB.NET

5.4. 使用128位元加密加密PDF

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-13.cs
// Save with a strong encryption password.
pdf.Password = "my.secure.password";
pdf.SaveAs("secured.pdf")
VB.NET

將其他 HTML 內容蓋章到 VB 頁面

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-14.cs
Imports IronPdf
Imports IronPdf.Editing

Module Module1
    Sub Main()
        Dim renderer = New ChromePdfRenderer
        Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
        Dim stamp = New HtmlStamper()
        stamp.Html = "<h2>Completed</h2>"
        stamp.Opacity = 50
        stamp.Rotation = -45
        stamp.VerticalAlignment = VerticalAlignment.Top
        stamp.VerticalOffset = New Length(10)
        pdf.ApplyStamp(stamp)
        pdf.SaveAs("C:\Path\To\Stamped.pdf")
    End Sub
End Module
VB.NET

5.6. 使用 HTML 向 PDF 添加分頁符

使用 HTML 和 CSS 是最簡單的方法。

:path=/static-assets/pdf/content-code-examples/how-to/vb-net-pdf-15.cs
<div style='page-break-after: always;'>&nbsp;</div>
HTML

6. 更多 .NET PDF 教程

您可能也會感興趣於:

查克尼思·賓
軟體工程師
Chaknith 致力於 IronXL 和 IronBarcode。他在 C# 和 .NET 方面擁有豐富的專業知識,協助改進軟體並支持客戶。他從用戶互動中獲得的洞察力有助於提高產品、文檔和整體體驗。