因此,我试图逐行读取文件并将其写入多个PDF,每个PDF文件应仅包含50行,如果一个PDF已满,则将创建另一个PDF,直到所有行都完成为止。
我快完成了。但是问题是每次只有第一个PDF都有内容。其他都空着。这是我的代码。
if ((System.IO.File.Exists(@"C:\Coil master 28-02-2019.csv")) == true)
{
int lineNumber = 1;
int PDFNumber = 0;
for (; PDFNumber < 4; PDFNumber++)
{
string path = Application.StartupPath;
var pgSize = new iTextSharp.text.Rectangle(2976, 4194);
Document pdfdoc = new Document(pgSize); // Setting the page size for the PDF
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(path + "/MasterCoils/" + (1 + (50 * PDFNumber)) + "-" + (50 + (PDFNumber * 50)) + ".pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
pdfdoc.Open(); // Opening the PDF to write the data from the textbox
foreach (string line in System.IO.File.ReadLines(@"C:\Coil master 28-02-2019.csv").Skip(1 + (50 * PDFNumber)).Take(50))
{
string[] inputArray = line.Split(delimiters); // split the input string by using the delimiter ','
COILID = inputArray[0];
TYPE = inputArray[1];
COLOR = inputArray[2];
WEIGHT = Int32.Parse(inputArray[3]);
GAUGE = inputArray[4];
WIDTH = inputArray[5];
PdfContentByte cb = writer.DirectContent;
// we tell the ContentByte we're ready to draw text
cb.BeginText();
// set up Font and Size for Content to be shown in PDF
BaseFont mybf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetFontAndSize(mybf, 15);
cb.SetTextMatrix(250 + (595 * i), (419 * (9 - j)) + 280);
cb.ShowText(COILID + "+" + TYPE + "+" + COLOR + "+" + WEIGHT + "+" + GAUGE + "+" + WIDTH);
// we tell the contentByte, we've finished drawing text
cb.EndText();
lineNumber++;
}
pdfdoc.Close();
}
}
如果删除foreach语句,则所有PDF都将包含一些内容。所以我想问题出在foreach,但是我找不到确切的地方。请给我一些帮助。谢谢!
答案 0 :(得分:0)
我运行了这段代码,它完全按预期工作,读取了一个csv并制作了4个新PDF,所有包含数据。
我唯一真正改变的是PDF的写入方式。
我不是ITextSharp专家,但希望对您有帮助。
if (File.Exists(@"Coil master 28-02-2019.csv") == true)
{
int fileNumber = 0;
for (; fileNumber < 4; fileNumber++)
{
var pgSize = new Rectangle(2976, 4194);
var pdfdoc = new Document(pgSize); // Setting the page size for the PDF
pdfdoc.Open(); // Opening the PDF to write the data from the textbox
foreach (string line in File.ReadLines("Coil master 28-02-2019.csv").Skip(1 + (50 * fileNumber)).Take(50))
{
string[] inputArray = line.Split(','); // split the input string by using the delimiter ','
var COILID = inputArray[0];
var TYPE = inputArray[1];
var COLOR = inputArray[2];
var WEIGHT = Int32.Parse(inputArray[3]);
var GAUGE = inputArray[4];
var WIDTH = inputArray[5];
var p = new Paragraph(COILID + "+" + TYPE + "+" + COLOR + "+" + WEIGHT + "+" + GAUGE + "+" + WIDTH);
pdfdoc.Add(p);
}
pdfdoc.Close();
}
}