首页 > 解决方案 > 使用 PdfSharp.Xamarin.Forms 创建 PDF 时无法显示 ListView 数据

问题描述

我是 xamarin 的新手,我正在使用 PdfSharp.Xamarin.Forms nuget 在 Xamarin 表单中为 Android 和 iOS 创建 PDF。问题是我无法渲染 ListView。他们已经提到了它,并且需要为它编写一个渲染器。但我不知道如何创建和绑定它。

我就是这样做的。

    <Grid x:Name="mainGrid">

        <ScrollView>

            <StackLayout Padding="4" Orientation="Vertical">

                <!--<Image HeightRequest="80" Source="logojpeg.jpg" Margin="0,0,0,5"/>-->

                <Label FontSize="18" TextColor="Black" FontFamily="{StaticResource timesNewRomanBold}" HorizontalOptions="CenterAndExpand" Text="Monthly Motor Renew List of Jayasekara (900585) as at January, 2020"/>
                <Label FontSize="18" TextColor="Black" FontFamily="{StaticResource timesNewRomanBold}" HorizontalOptions="CenterAndExpand" Text="Report generated on 27 December, 2019" Margin="0,0,0,5"/>

                <ListView x:Name="renewListView"
                              Footer=""
                              pdf:PdfRendererAttributes.ListRendererDelegate="{StaticResource PDFSampleListRendererDelegate}"
                              BackgroundColor="White"
                              SeparatorVisibility="None"
                              HasUnevenRows="True">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell IsEnabled="false">



                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

            </StackLayout>

        </ScrollView>

    </Grid>

在后面的代码中。

public partial class MotorRenewalFinalPrint : ContentPage
{
    public MotorRenewalFinalPrint()
    {
        InitializeComponent();
    }

    public MotorRenewalFinalPrint (List<MotorRenewalPrintData> newdd)
    {
        InitializeComponent ();
        Title = "Save as PDF";
        renewListView.ItemsSource = newdd;
    }

    private void pdf_Clicked(object sender, EventArgs e)
    {

        var pdf = PDFManager.GeneratePDFFromView(mainGrid);
        var fileManager = DependencyService.Get<IFileIO>();
        string filePath = Path.Combine(fileManager.GetMyDocumentsPath(), "formpdf.pdf");
        DependencyService.Get<IPdfSave>().Save(pdf, filePath);
        DependencyService.Get<IPDFPreviewProvider>().TriggerPreview(filePath);

    }
}

更新...

主类

public partial class MainPage : ContentPage
    {

        private List<Customer> Cus = new List<Customer>();

        public MainPage()
        {
            InitializeComponent();

            Customer ss1 = new Customer { Names = "test1", Ages = "10"};
            Customer ss2 = new Customer { Names = "test2", Ages = "30" };
            Cus.Add(ss1);
            Cus.Add(ss2);

            //rListView.ItemsSource = Cus;

        }

        private void Button_Clicked(object sender, System.EventArgs e)
        {
            var pdf = PDFManager.GeneratePDFFromView(mainGrid);
            var fileManager = DependencyService.Get<IFileIO>();
            string filePath = Path.Combine(fileManager.GetMyDocumentsPath(), "testpdf.pdf");
            DependencyService.Get<IPdfSave>().Save(pdf, filePath);
            DependencyService.Get<IPDFPreviewProvider>().TriggerPreview(filePath);
        }
    }

看法

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TestPDF"
             xmlns:pdf="clr-namespace:PdfSharp.Xamarin.Forms;assembly=PdfSharp.Xamarin.Forms"
             x:Class="TestPDF.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:PDFSampleListRendererDelegate  x:Key="PDFSampleListRendererDelegate" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>

        <Grid x:Name="mainGrid">

            <ScrollView>

                <StackLayout Margin="0,0,0,5">

                    <Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="CenterAndExpand" TextColor="Black" FontSize="18" VerticalOptions="Center" />

                    <ListView pdf:PdfRendererAttributes.ListRendererDelegate="{DynamicResource PDFSampleListRendererDelegate}" HeightRequest="150"/>

                    <Button Text="click" Clicked="Button_Clicked"/>

                </StackLayout>

            </ScrollView>

        </Grid>

    </ContentPage.Content>

</ContentPage>

PDFSampleListRendererDelegate

public class PDFSampleListRendererDelegate : PdfListViewRendererDelegate
{
    public override void DrawCell(ListView listView, int section, int row, XGraphics page, XRect bounds, double scaleFactor)
    {
        XFont font = new XFont("times" ?? GlobalFontSettings.FontResolver.DefaultFontName, 15);
        var yourObject = (listView.ItemsSource as List<Customer>).ElementAt(row);

        page.DrawString(yourObject.Names, font, XBrushes.Black, bounds,
        new XStringFormat
        {
            LineAlignment = XLineAlignment.Center,
            Alignment = XStringAlignment.Center,
        });
    }

    public override void DrawFooter(ListView listView, int section, XGraphics page, XRect bounds, double scaleFactor)
    {
        base.DrawFooter(listView, section, page, bounds, scaleFactor);
    }

    public override double GetFooterHeight(ListView listView, int section)
    {
        return base.GetFooterHeight(listView, section);
    }
}

标签: xamarinxamarin.forms

解决方案


你应该覆盖DrawCell方法

IE:

public override void DrawCell(ListView listView, int section, int row, XGraphics page, XRect bounds, double scaleFactor)
{
    XFont font = new XFont(yourCustomFont ?? GlobalFontSettings.FontResolver.DefaultFontName, label.FontSize * scaleFactor);
    var yourObject = (listView.ItemSource as List<YourObjType>).ElementAt(row);

    page.DrawString(yourObject.Text, font, XColors.Black, bounds,
    new XStringFormat {
        LineAlignment = XLineAlignment.Center,
        Alignment = XStringAlignment.Center,
    });
}

推荐阅读