You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iText7创建图片居左图表居右的PDF时遇显示问题求助

问题:iText7生成PDF时图片不显示且布局不符合预期

我正在使用iText7库及iText7.bouncy-castle-adapter包,想要生成一张包含图片和图表的PDF,要求图片位于图表左侧,下方附带文本"Additional text information about the histogram and image."。

我尝试了如下代码:

private void CreatePdf(string imagePath)
{
    string pdfPath = Path.Combine(Path.GetDirectoryName(imagePath), "Output.pdf");

    using (var pdfWriter = new PdfWriter(pdfPath))
    {
        using (var pdf = new PdfDocument(pdfWriter))
        {
            var document = new Document(pdf);

            // Create a table with two cells
            var table = new Table(2);
            table.UseAllAvailableWidth();

            // Add chart image to the first cell
            MemoryStream chartStream = new MemoryStream();
            chartHistogram.SaveImage(chartStream, ChartImageFormat.Png);
            var chartImage = new iTextImage(iText.IO.Image.ImageDataFactory.Create(chartStream.ToArray()));
            var chartCell = new Cell().Add(chartImage);
            table.AddCell(chartCell);

            // Add image from PictureBox to the second cell
            MemoryStream imageStream = new MemoryStream();
            pictureBoxImage.Image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png);
            var imageElement = new iTextImage(iText.IO.Image.ImageDataFactory.Create(imageStream.ToArray()));
            var imageCell = new Cell().Add(imageElement);
            table.AddCell(imageCell);

            // Add the table to the document
            document.Add(table);

            // Add text information
            Paragraph text = new Paragraph("Additional text information about the histogram and image.");
            document.Add(text);
        }
    }

    MessageBox.Show($"PDF created successfully: {pdfPath}", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

但实际生成的PDF中图表偏右,图片完全不显示。期望的效果是图片居左、图表居右,两者尺寸更大,下方带有指定文本。


问题分析与修正方案

问题点总结

  1. 图片不显示:MemoryStream写入图片数据后指针停留在流末尾,读取时无有效数据,需重置流位置
  2. 布局顺序错误:代码先添加图表到首单元格、图片到次单元格,导致布局与需求相反
  3. 尺寸过小:未配置图片缩放规则,显示尺寸不足
  4. 单元格布局松散:未设置单元格边距与内容对齐方式,导致布局偏移

修正后的代码

private void CreatePdf(string imagePath)
{
    string pdfPath = Path.Combine(Path.GetDirectoryName(imagePath), "Output.pdf");

    using (var pdfWriter = new PdfWriter(pdfPath))
    {
        using (var pdf = new PdfDocument(pdfWriter))
        {
            var document = new Document(pdf);
            // 设置文档边距,让内容更舒展
            document.SetMargins(20, 20, 20, 20);

            // 创建两列等宽表格(可调整数组比例修改列宽)
            var table = new Table(new float[] { 1, 1 });
            table.UseAllAvailableWidth();
            // 移除单元格默认边距,让图片占满单元格空间
            table.SetCellMargins(0);

            // 处理左侧图片:从PictureBox读取
            using (MemoryStream imageStream = new MemoryStream())
            {
                pictureBoxImage.Image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png);
                // 重置流指针到开头,确保iText能读取完整数据
                imageStream.Seek(0, SeekOrigin.Begin);
                var imageData = iText.IO.Image.ImageDataFactory.Create(imageStream.ToArray());
                var imageElement = new iTextImage(imageData);
                // 设置图片宽度占满列宽,高度自适应保持比例
                imageElement.SetWidth(table.GetColumnWidth(0));
                imageElement.SetAutoScaleHeight(true);

                // 创建左侧单元格,图片居中对齐
                var imageCell = new Cell().Add(imageElement).SetHorizontalAlignment(HorizontalAlignment.CENTER);
                table.AddCell(imageCell);
            }

            // 处理右侧图表
            using (MemoryStream chartStream = new MemoryStream())
            {
                chartHistogram.SaveImage(chartStream, ChartImageFormat.Png);
                chartStream.Seek(0, SeekOrigin.Begin);
                var chartData = iText.IO.Image.ImageDataFactory.Create(chartStream.ToArray());
                var chartImage = new iTextImage(chartData);
                chartImage.SetWidth(table.GetColumnWidth(1));
                chartImage.SetAutoScaleHeight(true);

                var chartCell = new Cell().Add(chartImage).SetHorizontalAlignment(HorizontalAlignment.CENTER);
                table.AddCell(chartCell);
            }

            // 添加表格到文档
            document.Add(table);

            // 添加下方文本,设置上边距避免与表格紧凑
            Paragraph text = new Paragraph("Additional text information about the histogram and image.")
                .SetMarginTop(10)
                .SetHorizontalAlignment(HorizontalAlignment.LEFT);
            document.Add(text);
        }
    }

    MessageBox.Show($"PDF created successfully: {pdfPath}", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

关键调整说明

  • 流指针重置:在写入图片后调用Seek(0, SeekOrigin.Begin),确保iText能读取完整的图片数据流
  • 布局顺序调换:先添加图片到首单元格,再添加图表到次单元格,实现图片居左、图表居右的需求
  • 图片尺寸控制:通过SetWidth让图片占满对应列宽,SetAutoScaleHeight(true)保持图片比例不变形
  • 表格优化:设置列宽比例、移除单元格边距、添加内容居中对齐,提升布局规整度
  • 文本样式调整:给文本添加上边距,避免与表格过于紧凑,提升整体美观度

内容的提问来源于stack exchange,提问作者Shien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:44:54