我已经通过
强调了“一些文字”var par = new Paragraph();
par.Add(new Chunk("Some text", CreateFont(12, Font.UNDERLINE)));
document.Add(par);
可以使用虚线(不是段落)强调“Some some text”?
由于
答案 0 :(得分:3)
This answer告诉您该怎么做但很遗憾没有提供任何代码,所以我在下面提供了这些代码。
据我所知,只有设置一个简单的属性,才能直接在iTextSharp中实现这一目标。相反,您需要使用PageEvent
并自己手动绘制线条。
首先你需要继承PdfPageEventHelper
:
private class UnderlineMaker : PdfPageEventHelper {
}
然后,您想要覆盖OnGenericTag()
方法:
public override void OnGenericTag(PdfWriter writer, Document document, iTextSharp.text.Rectangle rect, string text) {
}
text
变量将保存您稍后设置的任意值。这是一个包含评论的完整工作示例:
private class UnderlineMaker : PdfPageEventHelper {
public override void OnGenericTag(PdfWriter writer, Document document, iTextSharp.text.Rectangle rect, string text) {
switch (text) {
case "dashed":
//Grab the canvas underneath the content
var cb = writer.DirectContentUnder;
//Save the current state so that we don't affect future canvas drawings
cb.SaveState();
//Set a line color
cb.SetColorStroke(BaseColor.BLUE);
//Set a dashes
//See this for more details: http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfContentByte.html#setLineDash(float)
cb.SetLineDash(3, 2);
//Move the cursor to the left edge with the "pen up"
cb.MoveTo(rect.Left, rect.Bottom);
//Move to cursor to the right edge with the "pen down"
cb.LineTo(rect.Right, rect.Bottom);
//Actually draw the lines (the "pen downs")
cb.Stroke();
//Reset the drawing states to what it was before we started messing with it
cb.RestoreState();
break;
}
//There isn't actually anything here but I always just make it a habit to call my base
base.OnGenericTag(writer, document, rect, text);
}
}
以下是它的实现:
//Create a test file on the desktop
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Normal iTextSharp boilerplate, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Bind our helper class
writer.PageEvent = new UnderlineMaker();
//Create a new paragraph
var p = new Paragraph();
//Add a normal chunk
p.Add(new Chunk("This is a "));
//Create another chunk with an arbitrary tag associated with it and add to the paragraph
var c = new Chunk("dashed underline test");
c.SetGenericTag("dashed");
p.Add(c);
//Add the paragraph to the document
doc.Add(p);
doc.Close();
}
}
}
如果你想获得幻想,你可以将分隔的字符串传递给SetGenericTag()
,如dashed-black-2x4
或其他东西,然后在OnGenericTag
事件中解析出来。