簡體   English   中英

如何在 c# 中將 csv 轉換為 pdf

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

我需要將 csv 數據轉換為 PDF 文件。 使用 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();

    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);
            }
        }
    }

問題是每個條目的 output 不是換行,而是直接附加到前一個,在同一行中,如屏幕截圖所示:

在此處輸入圖像描述

以電子表格形式打開的原始文件如下所示

在此處輸入圖像描述

所需的output:

在此處輸入圖像描述

您正在創建一個包含 9 列的表:

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

這就是您看到意外行為的原因。

創建一個包含 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