Xamarin:在Xamarin.forms中将图像转换为Pdf格式

时间:2017-07-21 05:23:46

标签: xamarin uwp

我得到的错误宽度不能为null,当将图像传递给inputstream时。因为我没有找到任何alterante方法。基本上我想在支持UWP平台的Xamarin.forms中将图像转换为Pdf格式。 我正在使用xfinium pdf库。

public void ConvertJpegToPdf()
            {
                try
                {

                    PdfFixedDocument document = new PdfFixedDocument();
                    Xfinium.Pdf.PdfPage page = document.Pages.Add();
                    page.Width = 800;
                    page.Height = 600;

                    var imageStream = GetStream();
                    PdfJpegImage jpeg = new PdfJpegImage(imageStream);//<-Error

                    PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);

                    PdfBrush brush = new PdfBrush(PdfRgbColor.Red);

                    page.Graphics.DrawImage(jpeg, 0, 0, page.Width, page.Height);
                    Stream pdfStream = null;
                    document.Save(pdfStream);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

           }


    protected Stream GetStream()
            {
                byte[] byteArray = Encoding.UTF8.GetBytes("http://david.qservicesit.com/images/3.jpg");
                MemoryStream stream = new MemoryStream(byteArray);
                return stream;
            }
  

请建议替代方案

1 个答案:

答案 0 :(得分:0)

  

byte[] byteArray = Encoding.UTF8.GetBytes("http://david.qservicesit.com/images/3.jpg");

您无法以这种方式获取图像流。您使用的方法只能获得Bytes字符串。对于您的方案,您可以使用http客户端来获取图像流。请参考以下代码:

public async Task<Stream> GetStream()
{
    HttpClient client = new HttpClient();
    HttpResponseMessage res = await client.GetAsync(new Uri("http://david.qservicesit.com/images/3.jpg"));
    Stream stream = await res.Content.ReadAsStreamAsync();
    return stream;
}


public async Task ConvertJpegToPdf()
{
    try
    {
        PdfFixedDocument document = new PdfFixedDocument();
        Xfinium.Pdf.PdfPage page = document.Pages.Add();
        page.Width = 800;
        page.Height = 600;

        var imageStream = await GetStream();
        PdfJpegImage jpeg = new PdfJpegImage(imageStream);
        PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);
        PdfBrush brush = new PdfBrush(PdfRgbColor.Red);

        page.Graphics.DrawImage(jpeg, 0, 0, page.Width, page.Height);
        Stream pdfStream = new MemoryStream();
        document.Save(pdfStream);
    }
    catch (Exception ex)
    {
        throw ex;
    }

}