简体   繁体   English

如何在 c# 中将 csv 转换为 pdf

[英]How to convert csv to pdf in c#

I need to convert csv data to a PDF file.我需要将 csv 数据转换为 PDF 文件。 Using iText I have written this code:使用 iText 我编写了以下代码:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(pdfFile));
Document doc = new Document(pdfDoc, PageSize.A4.Rotate());

PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

iText.Layout.Element.Table table = new iText.Layout.Element.Table(UnitValue.CreatePercentArray(new float[] { 14, 6, 12, 16, 12, 12, 12, 12, 6 }));
using (BufferedReader br = new BufferedReader(new FileReader(excelFile)))
{
    String line = br.readLine();


    addRowToTable(table, line, bold, true);
    while ((line = br.readLine()) != null)
    {
        addRowToTable(table, line, font, false);
    }
}

doc.Add(table);

doc.Close();

and

    public void addRowToTable(iText.Layout.Element.Table table, String line, PdfFont font, Boolean isHeader)
    {


        StringTokenizer tokenizer = new StringTokenizer(line, ",");

        // Creates cells according to parsed csv line
    while (tokenizer.HasMoreTokens())
        {
            Cell cell = new Cell().Add(new Paragraph(tokenizer.NextToken(",")+"\r\n").SetFont(font));

            if (isHeader)
            {
                table.AddHeaderCell(cell);
            }
            else
            {
                table.AddCell(cell);
            }
        }
    }

The problem is that the output of each entry is not to new line, instead it appends directly to the previous one, in the same row, as the screen shot illustrates:问题是每个条目的 output 不是换行,而是直接附加到前一个,在同一行中,如屏幕截图所示:

在此处输入图像描述

The original file, opened as a spreadsheet, looks like this以电子表格形式打开的原始文件如下所示

在此处输入图像描述

The required output:所需的output:

在此处输入图像描述

You are creating a table with 9 columns:您正在创建一个包含 9 列的表:

new iText.Layout.Element.Table(
    UnitValue.CreatePercentArray(
        new float[] { 14, 6, 12, 16, 12, 12, 12, 12, 6 }
    )
);

That's why you see the unexpected behavior.这就是您看到意外行为的原因。

Create a table with 4 columns:创建一个包含 4 列的表:

new iText.Layout.Element.Table(
    UnitValue.CreatePercentArray(
        new float[] { 35, 15, 25, 25 }
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM