Printing JComponent

2020-08-01 05:56发布

问题:

I am required to be able to print a JComponent in a fashion so it looks awesome. Don't ask me what awesome is as I don't know either.

The JComponent is required to be too big for a page both in a x and y format. I am required to print the same JComponent into many pages split at a given y coordinate.

I have tried just scale the JComponent, though get problems to select a given y coordinate and to make it look good.

I have tried to change the JComponent to a given size, though then a given y coordinate is problematic, the JComponent don't look so good and I get lots of problems if the program is changed.

So now I sit here and don't know what to do as there seems to be a total lack of tutorials online on the topic...

How do Word and other text based programs accomplish this?

Best regards, Skarion

回答1:

This is a common problem I must say I faced it already. Useful for me were these tutorials:

  1. Tutorial1 --- It describes the problem shows how a page looks like etc.

  2. Tutorial2 --- Here you have nice working code example, which I have used in solving my problems. The author also presents use of scaling, translating, etc. for printing.

I hope it will help you too.

Maybe when you know more about what in your problem means awesome, I can help more. :)

EDIT1:

    double scale = 1;
    //scale only when component is wider then a page (page and component widths are doubles)
    if(componentWidth > pageWidth)
        scale = pageWidth/ componentWidth;
    //I first calculate where each page should end 
    //...
    //then when I paint a page I calculate translation over Y for each page
    double translateY = 0;
    //if page index grater then zero then take where the previous page ends
    if(pageIndex > 0)
        translateY = pageHeightEnds.get(pageIndex - 1);
    //shift Graphic to line up with beginning of next page to print
    g2.translate(0f, -translateY);

    g2.setClip(0, (int) Math.round(translateY),(int) Math.round(pageWidth), (int) Math.round(currentPageWidth));
    //  scale the page so the width fits...
    g2.scale(scala, scala);
    componentToPaint.paint(g2); 

Good luck, Boro.