Save CALayer to PDF (Vector Image)

Hi

I was forced to change from System.Drawing to CALayers, and now I can't figure out how to save the view to a PDF file.
Is is possible to save a CALayer as a vector PDF?

Thank you.

Answers

  • FrederikTheisenFrederikTheisen DKMember ✭✭

    I can't figure it out from that stack overflow thread.

    My current code works to some extend.
    It draws the PDF with shapes in vector format, however, text is drawn very badly. It's only the edges of the text that are drawn and it is very pixelated.

    Using DrawInContext instead of RenderInContext results in a blank PDF.
    Also, everything is flipped about the x axis.

    public void Print()
            {
                var imageName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "GeneViewerImage_" + DateTime.Now.ToString("u") + ".pdf");
    
                var url = NSUrl.FromFilename(imageName);
                var pdf = new CGContextPDF(url);
    
                pdf.BeginPage(VisibleRect());
    
                Layer.Dispose();
                Layer = SetupBackgroundLayer();
    
                OnPaint(Layer);
    
                Layer.RenderInContext(pdf);
    
                WantsLayer = true;
    
                pdf.EndPage();
                pdf.SaveState();
                pdf.Close();
            }
    

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    A few thoughts:

    • Maybe it is flipped because NSView use a different coordinate system?
    • Setting WantsLayer should be done before anything else, and only once.
    • You should not need to call Dispose by hand in most cases.
  • FrederikTheisenFrederikTheisen DKMember ✭✭

    I fixed the inverted image easily enough. I just flipped the PDF page around.
    WantsLayer can be moved, not sure if there is any difference. Apparently dispose is not needed either.

    Anyways, I found out the one can use CALayers or CGLayers. My current code is for CALayers, but since I'm not doing any animation, would it be better to use CGLayers? Most of my drawing code is located in a single class and I just call custom methods in that class when I want to draw a string or a circle or whatever.

    I managed to render text properly be going through the sublayers to my CALayer 'Layer'. However, then the other stuff will go missing and all the text is placed in the top left corner (0,0).

    Does anyone have experience with Xamarin and CG/CALayers and printing vector graphics?

Sign In or Register to comment.