我正在尝试使用ITextSharp
将文本添加到现有的pdf文件中。我完全不知道如何解决它。这是我到目前为止所尝试的。我想将wordDocContents附加到pdf文件中。我想在pdf文件的开头附加文本,因为pdf文件是空的。
using System;
using System.Web;
using System.Web.UI;
using TikaOnDotNet.TextExtraction;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace Project
{
public partial class Default : System.Web.UI.Page
{
public void button1Clicked(object sender, EventArgs args)
{
button1.Text = "You clicked me";
var textExtractor = new TextExtractor();
var wordDocContents = textExtractor.Extract("t.csv");
Console.WriteLine(wordDocContents);
Console.ReadLine();
generatepdffile();
}
protected void generatepdffile()
{
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("file1.pdf"), FileMode.Create));
}
}
}
' wordDocContents'中的内容如下。我的目标是将内容按照下面打印的方式附加到pdf文件中。
ACCOUNT_NUMBER,CUSTOMER_NAMES,VALUE_DATE,BOOKING_DATE,TRANSACTION,ACCOUNT_TYPE,BALANCE_TYPE,REFERENCE,MONEY.OUT,MONEY.IN,RUNNING.BALANCE,BRANCH,EMAIL,ACTUAL.BALANCE,AVAILABLE.BALANCE
1000000001,TEST,,2847899,KES,Account,,,10/10/2016,9/11/2016,15181800,UPPER HILL BRANCH,another@yahoo.com,5403.75,5403.75,
1000000001,,9/11/2016,9/11/2016,Opening Balance,,,,,,4643.22,,,,,
1000000001,,12/10/2016,12/10/2016,Mobile Mpesa Transfer,,,,1533,,3110.22,,,,,
1000000001,,17-10-2016,17-10-2016,ATM Withdrawal,,,6.29006E+11,1000,,2110.22,,,,,
1000000001,,17-10-2016,17-10-2016,ATM Withdrawal,,,6.29118E+11,2000,,110.22,,,,,
1000000001,,17-10-2016,17-10-2016,Mobile Mpesa Transfer,,,,2083,,-1972.78,,,,,
1000000001,,17-10-2016,17-10-2016,Transfer from Mpesa,,,,0,4000,2027.22,,,,,
1000000001,,18-10-2016,18-10-2016,Mobile Mpesa Transfer,,,,333,,1694.22,,,,,
以上问题不是建议的问题的重复,请看下面的链接。输出pdf的格式与链接中的格式完全不同。 https://postimg.org/image/tul7vxvrh/
答案 0 :(得分:0)
您可能需要使用提取的文本向pdf添加至少一个段落。
可能的helper可能是
private void AddParagraph(Document doc, int alignment, iTextSharp.text.Font font, iTextSharp.text.IElement content)
{
Paragraph paragraph = new Paragraph();
paragraph.SetLeading(0f, 1.2f);
paragraph.Alignment = alignment;
paragraph.Font = font;
paragraph.Add(content);
doc.Add(paragraph);
}
草拟使用的示例
private Font _largeFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD, BaseColor.BLACK);
void generatepdffile(string content)
{
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("file1.pdf"), FileMode.Create));
doc.Open();
AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk(content));
doc.Close();
}
从你的
之类的东西中调用generatepdffile(wordDocContents.Text);
您可以阅读有关生成pdf表here
的更多详细示例基本上,您应该从csv字符串拆分
创建表 PdfPTable table = new PdfPTable(colNum);
foreach (string line in content.Split('\n'))
{
foreach (string cellstr in line.Split(','))
{
PdfPCell cell = new PdfPCell(new Phrase(cellstr));
table.AddCell(cell);
}
}
AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, table);