Pdf generation 如何使用iTextSharp向PdfPCell添加不同的块?
如何使用iTextSharp(在生成PDF文件时)连接不同的块并将它们添加到段落、段落和单元格,然后将单元格添加到表中 我能够在生成PDF文件时找到某个“位置”,因此看起来是这样的(页面的右侧应该是空白的): 这是我使用的代码:Pdf generation 如何使用iTextSharp向PdfPCell添加不同的块?,pdf-generation,itextsharp,chunks,Pdf Generation,Itextsharp,Chunks,如何使用iTextSharp(在生成PDF文件时)连接不同的块并将它们添加到段落、段落和单元格,然后将单元格添加到表中 我能够在生成PDF文件时找到某个“位置”,因此看起来是这样的(页面的右侧应该是空白的): 这是我使用的代码: using (var ms = new MemoryStream()) { using (var doc = new Document(PageSize.A4, 50, 50, 25, 25)) { //Create a writer
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))
{
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
var courierBold11Font = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
var docTitle = new Paragraph("Mark Twain", courierBold11Font);
doc.Add(docTitle);
var timesRoman9Font = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
var subTitle = new Paragraph("Roughing It", timesRoman9Font);
doc.Add(subTitle);
var courier9RedFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
var importantNotice = new Paragraph("'All down but nine; set 'em up on the other alley, pard' - Scotty Briggs", courier9RedFont);
importantNotice.Leading = 0;
importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
PdfPTable table = new PdfPTable(1);
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.BorderWidth = PdfPCell.NO_BORDER;
table.WidthPercentage = 50;
table.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cellImportantNote);
doc.Add(table);
doc.Close();
}
var bytes = ms.ToArray();
String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
File.WriteAllBytes(testFile, bytes);
MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
}
}
但是,我需要分解红色文本,使其部分为粗体,部分为锚定标记/href,等等
我想我可以这样做:
var courier9RedBoldFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 9, BaseColor.RED);
// Build up chunkified version of "important notice"
Chunk boldpart = new Chunk("All down but nine - set 'em up on the other alley, pard", courier9RedBoldFont);
Chunk attribution = new Chunk("Scotty Briggs", courier9RedFont);
PdfPTable tbl = new PdfPTable(1);
tbl.WidthPercentage = 50;
tbl.HorizontalAlignment = Element.ALIGN_LEFT;
var par = new Paragraph();
par.Chunks.Add(boldpart);
par.Chunks.Add(attribution );
PdfPCell chunky = new PdfPCell(par);
chunky.BorderWidth = PdfPCell.NO_BORDER;
tbl.AddCell(chunky);
doc.Add(tbl);
…但这并不是在PDF文件中添加任何内容,但为什么不呢?单元格不包含段落吗?段落不能由块组成吗?而不是
para.Chunks.Add()
只需使用par.Add()
从段落
返回的块实际上来自基类短语
。如果对于该属性,您将看到返回的集合实际上是动态创建的临时集合,因此它实际上是只读的