Search code examples
c#pdfbitmapuwpsyncfusion

BitmapImage to PDF


i have some issues to create a PDF with Pictures inside. I know how to create a PDF but not how to Display Pictures inside. The Problem is, all function that i found does not Support BitmapImage. I tried ItextSharp and Syncfusion. Does anyone know how i can solve this Problem? Nearly all guides that i found is not able for UWP.

Here i tried to Convert the BitmapImage to System.IO.Stream but either this does not work.

StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(@"C:\Users\IT\source\repos\App3\App3");
try
{
    StorageFile file2 = await folder.GetFileAsync("test.pdf");
    await file2.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
catch
{

}
StorageFile file = await folder.CreateFileAsync("test.pdf");


using (Windows.Storage.Streams.IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    //Create a new PDF document.
    PdfDocument document = new PdfDocument();
    Stream s = writeStream.AsStream();
    //Add a page to the document.
    PdfPage page = document.Pages.Add();
    //Create PDF graphics for the page.
    PdfGraphics graphics = page.Graphics;
    foreach (var st in Waren)
    {
        StorageFolder folder2 = await StorageFolder.GetFolderFromPathAsync(@"C:\Users\IT\Pictures");
        StorageFile file2 = await folder2.GetFileAsync(st.Image + ".jpg");
        using (IRandomAccessStream stream = await file2.OpenAsync(FileAccessMode.Read))
        {

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
            WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
            bmp.SetSource(stream);

            // show the image in the UI if you want.
            byte[] buffer = null;

            using (MemoryStream ms = new MemoryStream())
            {
                Stream s1 = bmp.PixelBuffer.AsStream();
                s1.CopyTo(ms);

                buffer = ms.ToArray();
                Stream stream2 = new MemoryStream(buffer);
                PdfBitmap image = new PdfBitmap(stream2);
                //Draw the image
                graphics.DrawImage(image, 0, 0);
            }
        }
    }

    //Set the standard font.
    PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
    //Draw the text.
    graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
    //Save the document.
    document.Save(s);
    //Close the document.
    document.Close(true);

Solution

  • You're using the syncfusion UWP library in your project, so I helped you add syncfusion tag in your post.

    Back to your question. You wanted to draw images in your pdf file. Then, I refer to the syncfusion document to make a code sample for your reference:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
            //Creates an empty PDF document instance
            PdfDocument document = new PdfDocument();
    
            //Adding new page to the PDF document
            PdfPage page = document.Pages.Add();
    
            //Creates new PDF font
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
    
            //Drawing text to the PDF document
            page.Graphics.DrawString("Hello world", font, PdfBrushes.Black, 10, 10);
    
            StorageFile storageFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"panda.jpg");
    
            using (var filestream = await storageFile.OpenAsync(FileAccessMode.Read))
            {
                Stream st = filestream.AsStream();
                PdfBitmap pdfImage = new PdfBitmap(st);
                page.Graphics.DrawImage(pdfImage,0,20,500,500);
            }
    
            MemoryStream stream = new MemoryStream();
    
            //Saves the PDF document to stream
            await document.SaveAsync(stream);
    
            //Close the document
    
            document.Close(true);
    
            //Save the stream as PDF document file in local machine
    
            Save(stream, "Result.pdf");
    
    }
    
    async void Save(Stream stream, string filename)
    {
    
        stream.Position = 0;
        StorageFile stFile;
        if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
        {
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.DefaultFileExtension = ".pdf";
            savePicker.SuggestedFileName = "Sample";
            savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" });
            stFile = await savePicker.PickSaveFileAsync();
        }
        else
        {
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        }
        if (stFile != null)
        {
            Windows.Storage.Streams.IRandomAccessStream fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite);
            Stream st = fileStream.AsStreamForWrite();
            st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
            st.Flush();
            st.Dispose();
            fileStream.Dispose();
        }
    }
    

    enter image description here

    Please note that I put the image in the root directory of my project, If I want to get it from my code, I need to use Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"panda.jpg") method, and the files in InstalledLocation are read-only. You cannot write it.