Xfinium PDF:无法保存pdf文件。接收错误根缺失条目

时间:2016-05-19 05:26:03

标签: android pdf xamarin save

我在保存Xfinium PDF时遇到问题。我加载了一个文档,只是在页面上绘制线条并保存。生成的文件,但是当我使用该文件并加载回PdfFixedDocument时,我有错误

  

文件预告片

中缺少根条目

我的代码非常简单:

var pdf = new PdfFixedDocument (document.Location);
        var page = pdf.Pages [pageIndex];
        var graphics = page.Graphics;
        var directory = FileUtilities.GetExternalPrivateDirectory (PdfCore.CACHE_DIRECTORY);
        //var png = FileUtilities.GetFile (directory + "/test.pdf");  
        //var rawStream = File.OpenWrite (png.AbsolutePath);
        var stream = new FileStream (directory + "/test.pdf", FileMode.Create);
        pdf.BeginSave (stream);

        graphics.DrawLine(new Xfinium.Pdf.Graphics.PdfPen (),
            new Xfinium.Pdf.Graphics.PdfPoint (0,0),
            new Xfinium.Pdf.Graphics.PdfPoint (page.Width, page.Height));

        page.SaveGraphics (); 

        pdf.EndSave ();

2 个答案:

答案 0 :(得分:0)

不要手动创建流并使用BeginSave / EndSave,只需尝试使用Save

var pdf = new PdfFixedDocument();
var page = pdf.Pages.Add();
var graphics = page.Graphics;
                graphics.DrawLine(new Xfinium.Pdf.Graphics.PdfPen(),
    new Xfinium.Pdf.Graphics.PdfPoint(0, 0),
    new Xfinium.Pdf.Graphics.PdfPoint(page.Width, page.Height));
var directory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
pdf.Save(Path.Combine(directory.Path, "test.pdf"));

Java.IO.File pdfFILE = new Java.IO.File(Path.Combine(directory.Path, "test.pdf"));
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Uri.FromFile(pdfFILE), "application/pdf");
StartActivity(intent);

enter image description here

答案 1 :(得分:0)

我认为PDF文档未正确写入文件,因为该流未关闭。尝试在代码末尾添加这些行(在pdf.EndSave()之后):

stream.Flush();
stream.Close();

创建内容较重的页面(如矢量地图)时应使用BeginSave / SaveGraphics / EndSave模式,并希望在绘制一定数量的图形对象后调用SaveGraphics来减少内存消耗(SaveGraphics可以多次调用)对于页面)。

对于您的场景,您可以按如下方式简化代码(如SushiHangover建议):

var pdf = new PdfFixedDocument (document.Location);
var page = pdf.Pages [pageIndex];
var graphics = page.Graphics;

graphics.DrawLine(new Xfinium.Pdf.Graphics.PdfPen (),
    new Xfinium.Pdf.Graphics.PdfPoint (0,0),
    new Xfinium.Pdf.Graphics.PdfPoint (page.Width, page.Height));

var directory = FileUtilities.GetExternalPrivateDirectory(PdfCore.CACHE_DIRECTORY);
pdf.Save(directory + "/test.pdf");

免责声明:我为开发XFINIUM.PDF图书馆的公司工作。