gpt4 book ai didi

c# - 使用右对齐时 iTextSharp SetCharacterSpacing 损坏

转载 作者:行者123 更新时间:2023-11-30 15:33:30 30 4
gpt4 key购买 nike

我有一个包含两个单元格的表格。第一个单元格左对齐,第二个单元格右对齐。我还想更改文本的字符间距。我发现更改字符间距会破坏对齐方式,因此右对齐文本最终会超出表格的边界。

我在下面创建了一些测试代码,输出 PDF 的链接在此链接中

https://skydrive.live.com/redir?resid=1ECE2061CFF9124B!190&authkey=!ANcB0z_BN3N4UFo

是否有任何替代方法或变通方法来使字符间距与正确的对齐方式配合良好?

public void CharacterSpacingTest()
{
float margin = 50;

using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);

PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;

document.Open();

PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;

// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph("Hello World") { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);

// Change the character spacing
PdfContentByte cb = writer.DirectContent;
cb.SetCharacterSpacing(1f);

// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph("Hello World"));
cell2.BorderWidth = 1;
table.AddCell(cell2);

document.Add(table);

document.Close();

Blobs.SaveToFile(Blobs.LoadFromStream(stream), @"c:\Dev\test.pdf");
}
}

最佳答案

我已经设法通过使用 block 来设置字符间距来修复它。请参阅修改后的代码。

    public void CharacterSpacingTest()
{
float margin = 50;

using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);

PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;

document.Open();

PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;

// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph(GetChunk("Hello World")) { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);

// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph(GetChunk("Hello World")));
cell2.BorderWidth = 1;
table.AddCell(cell2);

document.Add(table);

document.Close();

Blobs.SaveToFile(Blobs.LoadFromStream(stream), @"c:\Dev\test.pdf");
}
}

private Chunk GetChunk(string text)
{
Chunk chunk = new Chunk(text);
chunk.SetCharacterSpacing(1);
return chunk;
}

关于c# - 使用右对齐时 iTextSharp SetCharacterSpacing 损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489800/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com