We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Aspose.PDF For NET 将图片转为PDF时,图片会被拉伸。

当我将图片转为PDF后,打开pdf,发现里面的图片被拉伸了,不再是原先的默认的样子。
我的代码如下:

Document doc = new Document();
// Add a page to pages collection of document
Page page = doc.Pages.Add();
// Load the source image file to Stream object
FileStream fs = new FileStream(@“C:\Users\howze\Desktop\test.jpg”, FileMode.Open, FileAccess.Read);
byte[] tmpBytes = new byte[fs.Length];
fs.Read(tmpBytes, 0, int.Parse(fs.Length.ToString()));

MemoryStream mystream = new MemoryStream(tmpBytes);
// Instantiate BitMap object with loaded image stream
Bitmap b = new Bitmap(mystream);

// Set margins so image will fit, etc.
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;

page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height);
// Create an image object
Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();
// Add the image into paragraphs collection of the section
page.Paragraphs.Add(image1);
// Set the image file stream
image1.ImageStream = mystream;
// Save resultant PDF file
doc.Save(@“C:\Users\howze\Desktop\out.pdf”);

图片转为pdf后,明显被拉伸了,图片本身是横版的,但是转为pdf后变成的竖版的,请问这个问题如何解决?如何让图片保持原本的样子。测试图片见附件。test.jpg (611.2 KB)

@howze

您是否可以更新代码段并设置Page.Height和Page.Width而不是设置Page.CropBox。请考虑使用以下代码段生成所需结果:

FileStream mystream = new FileStream(dataDir + "test.jpg", FileMode.Open);
Bitmap b = new Bitmap(mystream);
Document doc = new Document();
Page page = doc.Pages.Add();
// Set margins so image will fit, etc.
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;

page.PageInfo.Height = b.Height;
page.PageInfo.Width = b.Width;

// Create an image object
Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();
page.Paragraphs.Add(image1);
image1.ImageStream = mystream;
doc.Save(dataDir + "jpg2PDF.pdf");
mystream.Close();

非常非常感谢!
你成功解决了我的问题!

1 Like