在iText5中将生成的PDF页面上的所有文本上移或下移指定的数量-C#

时间:2019-02-01 16:50:33

标签: c# asp.net itext

我正在尝试添加一个选项,以将文本向下移动到使用iTextSharp 5生成的PDF中。以前,用户单击一个按钮即可生成PDF。现在,我添加了一个选项,他们单击相同的按钮,选择“顶部”,“中间”或“底部”,并生成相同的PDF,但是文本向下移动到中间,或者如果靠近,则移至页面底部不要选择顶部。我已经有了弹出窗口,并且已经为if语句设置了变量,我只需要在iText5中找到正确的命令即可根据Top,Middle或Bottom变量的if语句将添加到文档中的所有文本向下移动

这是我当前的代码,除了在线建议使用的“ moveText”命令外,其他所有命令都可以正常工作(iText7仅支持该命令(我也不确定该命令是否可以用于整个页面,或仍然需要指向特定段落。

iTextSharp.text.Document document = new 
iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
// Create an instance to the PDF file by creating an instance of the PDF 
// Writer class using the document and the filestrem in the constructor.      
// Open the document to enable you to write to the document 
document.Open();
// Set values of paragraphs
Chunk glue = new Chunk(new VerticalPositionMark());
Paragraph p1 = new Paragraph("CaseType: " + type, fontLb);
p1.Add(new Chunk(glue));
p1.Add("Date Filed: " + datefiled);
Chunk glue2 = new Chunk(new VerticalPositionMark());
Paragraph p2 = new Paragraph("Case No: " + caseno, fontLb);
p2.Add(new Chunk(glue2));
p2.Add("Amount of Suit: " + claim);
Paragraph p3 = new Paragraph("Section: " + divsec + "\n", fontLb);
p3.Alignment = Rectangle.ALIGN_LEFT;
Paragraph p4 = new Paragraph("AUSTIN BADON, CLERK", fontS);
p4.Alignment = Rectangle.ALIGN_CENTER;
Paragraph p5 = new Paragraph(caption, fontSb);
p5.Alignment = Rectangle.ALIGN_CENTER;
//Add previously defined paragraphs 
document.Add(p1); 
document.Add(p2); 
document.Add(p3); 
document.Add(p4); 
document.Add(p5); 
// Check if Middle or Bottom were selected, if so, move text down appropriate distance.
        if (btnFolderLblBot.Checked)
        {
            moveText(0, -400);
        }
        else if (btnFolderLblMid.Checked)
        {
            moveText(0, -200);            
        }
        else
        {
            moveText(0, 0);
        }
// Close the document
document.Close();
// Close the writer instance 
writer.Close();
// Always close open filehandles explicity
fs.Close();

明显的预期结果是,当btnFolderBot.Checked = true时,生成的PDF的整个文本向下移动到页面底部,当btnFolderMid.Checked = True时,生成的PDF的整个文本向下移动。到页面中间。如果btnFolderTop.Checked = true,或者由于某种原因无法正常工作,则文本完全不会移动。

1 个答案:

答案 0 :(得分:0)

我想出的解决方案(很可能不是最优雅的,因为我对iTextSharp和C#很陌生,)在正确设置3个复选框值之后使用了以下内容:

if (btnFolderLblBot.Checked)
        {
            document.SetMargins(40, 40, 522, 66);
        }
        else if (btnFolderLblMid.Checked)
        {
            document.SetMargins(40, 40, 306, 288);
        }
        else
        {
            document.SetMargins(40, 40, 81, 510);
        }

这很简单地更改了iTextSharp用于放置矩形的边距,有效地上下移动了矩形。在我的情况下,我试图将文本放置在顶部,中间或底部,以便在打印时贴在Avery标签上,因此让其余页面无法使用实际上对我来说是理想的选择。可能不是其他人希望移动文本,但仍然可以将整个页面用于其他文本。

相关问题