将PDF文件保存到Stream并从C#中加载PDF文件
Spire.PDF for .NET作为独立组件,与所有.NET开发平台兼容,使开发人员无需任何外部PDF阅读器或软件即可创建,读取,编写,编辑和处理PDF文件。在本节中,我将向您介绍如何创建PDF文件并将其保存为流,以及如何从流中加载PDF文件。
第一部分。创建PDF文件并将其保存为流
第1步:新建PDF实例。
PdfDocument doc = new PdfDocument();
第2步:创建一个页面。
PdfPageBase page = doc.Pages.Add();
第3步:向该页面添加文本。
page.Canvas.DrawString(“Hello, World!”,
new PdfFont(PdfFontFamily.Helvetica, 30f),
new PdfSolidBrush(Color.Black),
10, 10);
第4步:将PDF文件保存到Stream。
FileStream to_strem = new FileStream(“To_stream.pdf”, FileMode.Open);
doc.SaveToStream(to_stream);
to_stream.Close();
doc.Close();
第二部分。从流中加载PDF文件
第1步:新建PDF实例。
PdfDocument doc = new PdfDocument();
第2步:从流中加载PDF文件。
FileStream from_stream = File.OpenRead(“sample.pdf”);
doc.LoadFromStream(from_stream);
第3步:保存PDF文档。
doc.SaveToFile(“From_stream.pdf”,FileFormat.PDF);
System.Diagnostics.Process.Start(“From_stream.pdf”);
完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Pdf;
using System.IO;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace PdfAndStream
{
class Program
{
static void Main(string[] args)
{
//A: 创建PDF文件并保存到流
//create a pdf document.
PdfDocument doc = new PdfDocument();
//创建一个页面
PdfPageBase page = doc.Pages.Add();
//画出文字
page.Canvas.DrawString("Hello, World!",
new PdfFont(PdfFontFamily.Helvetica, 30f),
new PdfSolidBrush(Color.Black),
10, 10);
//将pdf文件保存到Stream
FileStream to_stream = new FileStream("To_stream.pdf", FileMode.Open);
doc.SaveToStream(to_stream);
to_stream.Close();
doc.Close();
System.Diagnostics.Process.Start("To_stream.pdf");
// B:从Stream加载PDF文件
//创建一个pdf文档。
PdfDocument docFrom = new PdfDocument();
//从流加载PDF文件
FileStream from_stream = File.OpenRead("sample.pdf");
docFrom.LoadFromStream(from_stream);
//保存pdf文档
docFrom.SaveToFile("From_stream.pdf",FileFormat.PDF);
System.Diagnostics.Process.Start("From_stream.pdf");
}
}
}
作者:刘联其
来源:优快云
原文:https://blog.youkuaiyun.com/qqqqqqqqqq198968/article/details/85091042
版权声明:本文为博主原创文章,转载请附上博文链接!