如何在 Xamarin Forms 中生成 PDF 第一页的缩略图
Posted
技术标签:
【中文标题】如何在 Xamarin Forms 中生成 PDF 第一页的缩略图【英文标题】:How to generate the Thumbnail of the PDF first page in Xamarin Forms 【发布时间】:2019-04-29 12:42:44 【问题描述】:我正在使用 Xamarin Forms 的 Syncfusion PDF 查看器来显示 PDF 文件的集合,并且似乎从 PDF 转换为 PNG(提取 PDF 文件的第一页(封面)以显示它,到用户,进入轮播)在 Xamarin 中不起作用 [参见 https://www.syncfusion.com/kb/9112/how-to-convert-pdf-to-png]
我想知道是否有办法在 Xamarin 平台上将 PDF 转换为 PNG,或者我是否应该在服务器端进行转换。
谢谢。
【问题讨论】:
关于pdf转png请看***.com/questions/23905169/… 我知道如何将 PDF 转换为 png(使用ImageMagik
)。当我使用 Xamarin Forms 时,我的问题是关于在设备(即时)、android/ios 智能手机/平板电脑上执行此操作,或者我是否必须在 Web 服务器端执行此操作并提供设备的下载链接.
【参考方案1】:
您可以通过使用 PdfRenderer、CGPDFDocument 和 PdfDocument 类将 PDF 页面导出为图像,而无需使用 Syncfusion PDF 查看器控件。
Xamarin.Forms.Android:
//initialize PDFRenderer by passing PDF file from location.
PdfRenderer renderer = new PdfRenderer(GetSeekableFileDescriptor());
int pageCount = renderer.PageCount;
for(int i=0;i<pageCount;i++)
// Use `openPage` to open a specific page in PDF.
Page page = renderer.OpenPage(i);
//Creates bitmap
Bitmap bmp = Bitmap.CreateBitmap(page.Width, page.Height, Bitmap.Config.Argb8888);
//renderes page as bitmap, to use portion of the page use second and third parameter
page.Render(bmp, null, null, PdfRenderMode.ForDisplay);
//Save the bitmap
SaveImage(bmp);
page.Close();
//Method to retrieve PDF file from the location
private ParcelFileDescriptor GetSeekableFileDescriptor()
ParcelFileDescriptor fileDescriptor = null;
try
string root = Android.OS.Environment.ExternalStorageDirectory.ToString()+ "/Syncfusion/sample.pdf";
fileDescriptor = ParcelFileDescriptor.Open(new Java.IO.File(root),ParcelFileMode.ReadOnly
);
catch (FileNotFoundException e)
return fileDescriptor;
Xamarin.Forms.iOS:
public void ConvertToImage(Stream fileStream) //Pass PDF stream
MemoryStream stream = new MemoryStream();
// Create memory stream from file stream.
fileStream.CopyTo(stream);
// Create data provider from bytes.
CGDataProvider provider = new CGDataProvider(stream.ToArray());
try
//Load a PDF file.
m_pdfDcument = new CGPDFDocument(provider);
catch (Exception)
//Get PDF's page and convert as image.
using (CGPDFPage pdfPage = m_pdfDcument.GetPage(2))
//initialise image context.
UIGraphics.BeginImageContext(pdfPage.GetBoxRect(CGPDFBox.Media).Size);
// get current context.
CGContext context = UIGraphics.GetCurrentContext();
context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
// Gets page's bounds.
CGRect bounds = new CGRect(pdfPage.GetBoxRect(CGPDFBox.Media).X, pdfPage.GetBoxRect(CGPDFBox.Media).Y, pdfPage.GetBoxRect(CGPDFBox.Media).Width, pdfPage.GetBoxRect(CGPDFBox.Media).Height);
if (pdfPage != null)
context.FillRect(bounds);
context.TranslateCTM(0, bounds.Height);
context.ScaleCTM(1.0f, -1.0f);
context.ConcatCTM(pdfPage.GetDrawingTransform(CGPDFBox.Crop, bounds, 0, true));
context.SetRenderingIntent(CGColorRenderingIntent.Default);
context.InterpolationQuality = CGInterpolationQuality.Default;
// Draw PDF page in the context.
context.DrawPDFPage(pdfPage);
// Get image from current context.
pdfImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
// Get bytes from UIImage object.
using (var imageData = pdfImage.AsPNG())
imageBytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, imageBytes, 0, Convert.ToInt32(imageData.Length));
//return bytes;
//Create image from bytes.
imageStream = new MemoryStream(imageBytes);
//Save the image. It is a custom method to save the image
Save("PDFtoImage.png", "image/png", imageStream);
Xamarin.Forms.UWP
public async void ConvertToImage(Stream fileStream) //Pass PDF stream
StorageFile file = null;
//Creates file picker to choose PDF file.
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".pdf");
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
filePicker.SettingsIdentifier = "picker1";
filePicker.CommitButtonText = "Open Pdf File";
//Open file picker option
file = await filePicker.PickSingleFileAsync();
// Load selected PDF file from the file picker.
PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(file);
if (pdfDocument != null && pdfDocument.PageCount > 0)
for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
//Get page from a PDF file.
var pdfPage = pdfDocument.GetPage((uint)pageIndex);
if (pdfPage != null)
//Create temporary folder to store images.
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
//Create image file.
StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync(Guid.NewGuid().ToString() + ".jpg");
if (destinationFile != null)
IRandomAccessStream randomStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite);
//Crerate PDF rendering options
PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions();
pdfPageRenderOptions.DestinationWidth = (uint)(300);
// Render the PDF's page as stream.
await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions);
await randomStream.FlushAsync();
//Dispose the random stream
randomStream.Dispose();
//Dispose the PDF's page.
pdfPage.Dispose();
我为 Syncfusion 工作。
【讨论】:
以上是关于如何在 Xamarin Forms 中生成 PDF 第一页的缩略图的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin.Forms 将文件 (pdf) 保存在本地存储中并使用默认查看器打开
Xamarin.Forms 未能使用 EvoHtmlToPdfclient 将 html 字符串转换为 pdf 文件
Xamarin.Forms 在 webview 中打开来自 https://docs.google.com/viewer?url=pdf 的 url