内容目录
The source file is a PDF composed of various points, lines, text, and tables, and all content needs to be converted into image format and stored in a PDF.
Introduction:
<ItemGroup>
<PackageReference Include="FreeSpire.PDF" Version="8.6.0" />
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="2.3.2" />
</ItemGroup>
internal class Program
{
private static readonly RecyclableMemoryStreamManager StreamManager = new();
[SupportedOSPlatform("windows")]
static async Task Main()
{
using PdfDocument oldPdf = new PdfDocument();
using PdfDocument newPdf = new PdfDocument();
oldPdf.LoadFromFile("old.pdf");
for (int i = 0; i < oldPdf.Pages.Count; i++)
{
PdfPageBase oldPage = oldPdf.Pages[i];
var newPage = newPdf.AppendPage();
// Convert the page to an image
Image image = oldPdf.SaveAsImage(i, PdfImageType.Bitmap);
using var stream = StreamManager.GetStream();
image.Save(stream, ImageFormat.Png);
// Insert the image into the new PDF page
var pdfImage = PdfImage.FromStream(stream);
var size = GetSize(newPage, image);
// Draw image and set coordinates
newPage.Canvas.DrawImage(pdfImage, new PointF(0, 0), size);
}
newPdf.SaveToFile("new.pdf");
}
/// <summary>
/// Resize image<br />
/// If the image is too long or large, it will be automatically reduced.<br />
/// If the image is small, it will be centered horizontally.
/// </summary>
/// <param name="page"></param>
/// <param name="image"></param>
/// <returns></returns>
[SupportedOSPlatform("windows")]
static SizeF GetSize(PdfPageBase page, Image image)
{
float x = 0; // X coordinate of the image on the page
// float y = 0; // Y coordinate of the image on the page
float imageWidth = image.Width;
float imageHeight = image.Height;
// ClientSize gives the actual displayable area after removing borders; Size is the full paper area
var clientSize = page.GetClientSize();
float pageWidth = clientSize.Width;
float pageHeight = clientSize.Height;
// Final calculated results
float width = image.Width;
float height = image.Height;
// If the image is too long
if (imageWidth >= pageWidth)
{
float ratio = imageWidth / pageWidth;
width = pageWidth;
height = imageHeight / ratio;
}
// Center the image if it is smaller than the page
else if (imageHeight < pageWidth)
{
x = (pageWidth - imageWidth) / 2;
}
return new SizeF(width: width, height: height);
}
}
文章评论