PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outputPath, FileMode.Create)) 未将对象引用设置到对象的
时间: 2023-11-28 13:48:11 浏览: 38
这个错误通常是因为 `doc` 对象为空引起的。请确保在调用 `GetInstance` 方法之前,`doc` 对象已经被正确地初始化了,例如:
```csharp
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outputPath, FileMode.Create));
```
如果还出现问题,可以检查 `outputPath` 是否正确设置,以及当前用户是否具有写入该文件的权限。
相关问题
// 使用 NPOI 创建 PDF 文件 FileStream pdfStream = new FileStream("output.pdf", F
以下是使用NPOI将Excel文件转换为PDF文件的示例代码:
```csharp
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
//读取Excel文件
using (FileStream stream = new FileStream("path/to/excel/document", FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (Path.GetExtension("path/to/excel/document").Equals(".xls"))
{
workbook = new HSSFWorkbook(stream);
}
else if (Path.GetExtension("path/to/excel/document").Equals(".xlsx"))
{
workbook = new XSSFWorkbook(stream);
}
//将Excel文件转换为PDF格式
using (FileStream pdfStream = new FileStream("path/to/pdf/document", FileMode.Create, FileAccess.Write))
{
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
ISheet sheet = workbook.GetSheetAt(i);
if (sheet == null) continue;
pdfDoc.NewPage();
PdfPTable table = new PdfPTable(sheet.GetRow(0).LastCellNum);
for (int j = 0; j < sheet.GetRow(0).LastCellNum; j++)
{
string cellValue = sheet.GetRow(0).GetCell(j).ToString();
table.AddCell(new Phrase(cellValue));
}
for (int k = 1; k <= sheet.LastRowNum; k++)
{
IRow row = sheet.GetRow(k);
if (row == null) continue;
for (int l = 0; l < row.LastCellNum; l++)
{
string cellValue = row.GetCell(l).ToString();
table.AddCell(new Phrase(cellValue));
}
}
pdfDoc.Add(table);
}
pdfDoc.Close();
}
}
```
该代码使用了iTextSharp库来将Excel文件转换为PDF格式,并且支持同时转换多个Sheet。
iTextSharp 转pdf
以下是使用iTextSharp库将文本转换为PDF的示例代码:
```csharp
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class Program
{
public static void Main(string[] args)
{
// 创建一个新的PDF文档
Document document = new Document();
// 指定PDF文件的输出路径
string outputPath = "output.pdf";
// 创建一个PDF写入器,将文档写入到指定的输出路径
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
// 打开文档
document.Open();
// 添加内容到文档
document.Add(new Paragraph("Hello, World!"));
// 关闭文档
document.Close();
Console.WriteLine("PDF文件已生成:" + outputPath);
}
}
```
请注意,你需要在你的项目中添加对iTextSharp库的引用。可以通过在.csproj文件中的ItemGroup节点中添加以下引用来实现:
```xml
<PackageReference Include="iTextSharp" Version="5.5.13.2" />
```