Kar*_*hik 2 c# pdf asp.net itextsharp
我一直在使用iTextSharp来创建报告.我的报告中有许多不同大小的图像.尽管我缩放它们,但每个图像都会呈现不同的大小.我找到了许多解决方案但没有帮助.
我的代码:
PdfPCell InnerCell;
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath(@"images\Logo.png"));
logo.ScaleToFit(80f, 80f);
InnerCell.FixedHeight = 80f;
InnerCell = new PdfPCell(logo);
Run Code Online (Sandbox Code Playgroud)
我尝试将图像添加到块中,但图像将其自身置于顶部.由于是动态报告,我无法在块中指定x和y值
InnerCell = new PdfPCell(new Phrase(new Chunk(logo, 0, 0)));
Run Code Online (Sandbox Code Playgroud)
我甚至试过这个,但我不能得到一个固定的大小.
ScaleToFit(w,h)将根据源图像的宽度/高度中的较大者按比例缩放图像.缩放多个图像时,除非尺寸的比例都相同,否则最终会有不同的尺寸.这是设计的.
使用ScaleToFit(80,80):
100x100你就会得到一个正方形80x80200x100那么您将获得一个矩形80x40100x200那么您将获得一个矩形40x80无论出现什么,测量宽度和高度,至少一个将是您指定的尺寸之一.
我创建了一个创建随机大小图像的示例程序,它给了我图像中显示的预期输出(w = 80,h = 80,h = 80,h = 80,w = 80)

private void test() {
//Output the file to the desktop
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard PDF creation here, nothing special
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Create a random number generator to create some random dimensions and colors
var r = new Random();
//Placeholders for the loop
int w, h;
Color c;
iTextSharp.text.Image img;
//Create 5 images
for (var i = 0; i < 5; i++) {
//Create some random dimensions
w = r.Next(25, 500);
h = r.Next(25, 500);
//Create a random color
c = Color.FromArgb(r.Next(256), r.Next(256), r.Next(256));
//Create a random image
img = iTextSharp.text.Image.GetInstance(createSampleImage(w, h, c));
//Scale the image
img.ScaleToFit(80f, 80f);
//Add it to our document
doc.Add(img);
}
doc.Close();
}
}
}
}
/// <summary>
/// Create a single solid color image using the supplied dimensions and color
/// </summary>
private static Byte[] createSampleImage(int width, int height, System.Drawing.Color color) {
using (var bmp = new System.Drawing.Bitmap(width, height)) {
using (var g = Graphics.FromImage(bmp)) {
g.Clear(color);
}
using (var ms = new MemoryStream()) {
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为你正在寻找的是能够按比例缩放图像,但也有"大小"的图像,这意味着用透明或可能是白色像素填充其余像素.请参阅此文章以获得解决方案.
| 归档时间: |
|
| 查看次数: |
9385 次 |
| 最近记录: |