我使用Itext生成pdf,我需要做一些像Chunk.keepOnSameLine。
我正在构建一个可以有多个由多个Chunks组成的行的短语,当行结束时,我希望块不被破坏。
Chunk是一个名字和日期。例如:"约翰史密斯(2016-01-13 11:13)"
代码就像
Phrase p = new Phrase();
Chunk c1 = new Chunk("FirstName LastName (2016-01-13 11:13)");
p.Add(c1);
Chunk c2 = new Chunk("FirstName LastName (2016-01-13 11:13)")
p.Add(c2);
Chunk c3 = new Chunk("FirstName LastName (2016-01-13 11:13)")
p.Add(c3);
Chunk c4 = new Chunk("FirstName LastName (2016-01-13 11:13)")
p.Add(c4);
Chunk c5 = new Chunk("FirstName LastName (2016-01-13 11:13)")
p.Add(c5);
Chunk c6 = new Chunk("FirstName LastName (2016-01-13 11:13)")
p.Add(c6);
Chunk c7 = new Chunk("FirstName LastName (2016-01-13 11:13)")
p.Add(c7);
(代码是动态的,所以我不知道会有多少块。
结果短语显示为
然后将得到的短语添加到PdfPCell
答案 0 :(得分:3)
您可以修改iText如何通过实施ISplitCharacter
并用您自己的替换默认值(连字符和空格)来分割行:
public class CustomSplitCharacter : ISplitCharacter
{
public bool IsSplitCharacter(
int start, int current, int end, char[] cc, PdfChunk[] ck)
{
char c = ck == null
? cc[current]
: (char)ck[Math.Min(current, ck.Length - 1)]
.GetUnicodeEquivalent(cc[current])
;
return (c == ')');
}
}
然后在SetSplitCharacter()
上致电Chunk
:
string chunkText = "FirstName LastName (2016-01-13 11:13)";
Random random = new Random();
var font = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD);
using (Document document = new Document())
{
PdfWriter.GetInstance(document, stream);
document.Open();
Phrase phrase = new Phrase();
for (var i = 0; i < 1000; ++i)
{
var asterisk = new String('*', random.Next(1, 20));
Chunk chunk = new Chunk(
string.Format("[{0}] {1}", asterisk, chunkText),
font
);
chunk.SetSplitCharacter(new CustomSplitCharacter());
phrase.Add(chunk);
}
document.Add(phrase);
}
这假设您的Chunk
以)
结尾,就像您的示例代码一样,或者您可以控制Chunk
的最后一个文字字符。
不依赖于特定字体。 :)
答案 1 :(得分:0)
使用non-breaking space的Unicode U+00A0
。您还需要使用U+2011
,non-breaking hyphen。但是,非破坏连字符在技术上与普通连字符的字符不同,所以你也需要一种支持它的字体。
var testString = "FirstName LastName (2016-01-13 11:13)";
var nbsp = "\u00a0";
var nbhy = "\u2011";
//With a normal space
var p1 = new Phrase();
for (var i = 0; i < 100; i++) {
p1.Add(new Chunk(testString + " "));
}
doc.Add(p1);
//Create a font that supports our "hard hyphen"
var bf = BaseFont.CreateFont(fontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var f = new iTextSharp.text.Font(bf, 12);
testString = testString.Replace(" ", nbsp).Replace("-", nbhy);
//With a non-breaking space
var p2 = new Phrase();
for (var i = 0; i < 100; i++) {
p2.Add(new Chunk(testString + " ", f));
}
doc.Add(p2);