繁体   English   中英

在 C# 中创建一个包含列表内容的 pdf 文件

[英]Create a pdf file with the content of a list in C#

我正在尝试创建一个包含列表内容的 pdf 文件。

我以这种方式创建了列表:

            int arrayLength = obj.records.Count;
            List<string> outPutList = new List<string>();
            

            for (int i = 0; i<arrayLength; i++)
            {
                str = "";
                str = obj.records[i].datetime + "         " + obj.records[i].userName + "              " + obj.records[i].inTime + "               " + obj.records[i].outTime;
                outPutList.Add(str);
                Console.WriteLine(str);

我在互联网上发现了一些 C# 示例代码,通常允许我创建包含我想要的内容的 pdf:

            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4);
            float y = 30;

            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new System.Drawing.Font("Impact", 18f, FontStyle.Regular), true);
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Rapport", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            
            y = y + font1.MeasureString("Rapport", format1).Height;
            
            y = y + 5;

            
            PdfList list = new PdfList(str);
            
            PdfLayoutResult result = list.Draw(page, 1, y);
            
            y = result.Bounds.Bottom;

            doc.SaveToFile("List.pdf"); 
            doc.Close();
            System.Diagnostics.Process.Start("List.pdf");

似乎可行,但 pdf 只有我创建的列表的最后一行,而不是全部内容。

你知道问题可能是什么吗? 为什么我只得到最后一行而不是列表的全部内容?

感谢您的帮助。

正如我在评论中提到的,您覆盖了str变量的值。 您想要做的是以下内容:(我添加了一个额外的变量让您了解=+=运算符之间的区别):

int arrayLength = obj.records.Count;
List<string> outPutList = new List<string>();

// Add new variable as empty string
string content = "";

for (int i = 0; i<arrayLength; i++)
{
    // give str new value
    str = "";
    // give str new value again
    str = obj.records[i].datetime + "         " + obj.records[i].userName + "              " + obj.records[i].inTime + "               " + obj.records[i].outTime;
    outPutList.Add(str);
    Console.WriteLine(str);
    
    // append str to content variable with old en new value
    content += str;
        

然后在PdfList实例的初始化中传递content变量:

// Pass content variable to PdfList
PdfList list = new PdfList(content);

有关此运算符的更详细说明,请阅读https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/addition-operator

我希望这可以帮助你 :)

暂无
暂无

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

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