BitmapImage to PDF - PullRequest
       27

BitmapImage to PDF

0 голосов
/ 26 апреля 2018

У меня есть некоторые проблемы при создании PDF с изображениями внутри. Я знаю, как создать PDF, но не умею отображать картинки внутри. Проблема в том, что все функции, которые я обнаружил, не поддерживают BitmapImage. Я попробовал ItextSharp и Syncfusion. Кто-нибудь знает, как я могу решить эту проблему? Почти все руководства, которые я нашел, не в состоянии для UWP.

Здесь я попытался преобразовать BitmapImage в System.IO.Stream, но либо это не работает.

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);

1 Ответ

0 голосов
/ 27 апреля 2018

Вы используете библиотеку syncfusion UWP в своем проекте, поэтому я помог вам добавить тег syncfusion в ваше сообщение.

Вернуться к вашему вопросу. Вы хотели нарисовать изображения в вашем файле PDF. Затем я обращаюсь к документу syncfusion , чтобы сделать пример кода для вашей справки:

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

Обратите внимание, что я помещаю изображение в корневой каталог моего проекта. Если я хочу получить его из своего кода, мне нужно использовать метод Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"panda.jpg"), а файлы в InstalledLocation доступны только для чтения. Вы не можете написать это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...