在 iTextSharp(.NET 版 PDF 操作库)中,两个表格间距设为 0 核心是:清除表格的默认边距、间距,并用 PdfPTable.SpacingBefore = 0 强制消除上方间距。
直接给你可直接复制运行的完整代码 ,保证两个表格无缝贴合、间距为 0。
一、最终可用代码(C#)
csharp
运行
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace iTextSharpTableZeroSpacing
{
class Program
{
static void Main(string[] args)
{
// 1. 创建文档
Document doc = new Document(PageSize.A4);
// 2. 创建PDF写入流
string outputPath = "TwoTablesZeroSpacing.pdf";
PdfWriter.GetInstance(doc, new FileStream(outputPath, FileMode.Create));
// 3. 打开文档
doc.Open();
// ==============================================
// 第一个表格
// ==============================================
PdfPTable table1 = new PdfPTable(1); // 1列
table1.DefaultCell.Border = Rectangle.BOX; // 显示边框方便看间距
table1.AddCell("表格 1");
// 关键:清除所有边距
table1.SpacingAfter = 0; // 表格下方间距 = 0
// 添加到文档
doc.Add(table1);
// ==============================================
// 第二个表格(关键:SpacingBefore = 0)
// ==============================================
PdfPTable table2 = new PdfPTable(1);
table2.DefaultCell.Border = Rectangle.BOX;
table2.AddCell("表格 2");
// 核心:设置表格**上方间距 = 0**(消除和上一个表格的距离)
table2.SpacingBefore = 0;
table2.SpacingAfter = 0;
// 添加第二个表格
doc.Add(table2);
// 4. 关闭文档
doc.Close();
Console.WriteLine($"PDF 已生成:{outputPath}");
Console.ReadLine();
}
}
}
二、让两个表格间距为 0 的3 个关键属性
只要给表格设置这 3 个值,间距就一定是 0:
-
table1.SpacingAfter = 0第一个表格底部不留间距 -
table2.SpacingBefore = 0第二个表格顶部不留间距(最关键)
三、如果你想完全无缝、连边框都贴在一起
再额外加一句:
csharp
运行
// 让表格紧贴文档边缘,不产生默认留白
table1.WidthPercentage = 100;
table2.WidthPercentage = 100;
总结
- 两个表格间距为 0 =
SpacingAfter=0+SpacingBefore=0 - 必须给第二个表格 设置
SpacingBefore = 0
//取网站的域名,协议、端口、当前站点目录的地址
cs
string urlCode = "http://job.xxx.com:9248/#/pages/businessProcess/PurApply_Detail?Fid=" + FKEYVALUE;
string picCode = this.baseDir + "PurApply_" + FKEYVALUE + ".jpg";
urlCode = Globals.CreateQRCode(urlCode, picCode, false, ImageFormats.Jpeg);
string url = HttpContext.Current.Request.Url.ToString();
Uri uri = new Uri(url);
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
string fileDate = usersInfo.UserID + "_" + FKEYVALUE;
string fileNamePdf = requested + "/FilePDF/PurApply/" + fileDate + ".pdf";
string fileNamePdf2 = System.AppDomain.CurrentDomain.BaseDirectory + "/FilePDF/PurApply/" + fileDate + ".pdf";
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 15, 15, 15, 15);
object value = PdfWriter.GetInstance(doc, new FileStream(fileNamePdf2, FileMode.Create));
doc.Open();