简体   繁体   中英

How to convert csv to pdf in c#

I need to convert csv data to a PDF file. Using iText I have written this code:

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:

在此处输入图像描述

The original file, opened as a spreadsheet, looks like this

在此处输入图像描述

The required output:

在此处输入图像描述

You are creating a table with 9 columns:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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