5

I have a Visualforce page where I need to show the chatter posts in a PDF. The chatter post is generated by apex code and contains new line characters. I am querying the posts and displaying them inside a pdf.

The chatter post format in the Visualforce PDF is different from than original post by the new lines. The PDF shows the post as continuous text, and is not allowing the line breaks according to the \n used. Is there any way to achieve this? Or is the PDF format not supporting \n inside?

2 Answers 2

11

You can either wrap the text in a <pre> tag or give the container a style of white-space: pre;

<apex:page renderAs="pdf">
    <apex:outputPanel style="white-space: pre;" layout="block">

        herp derp


        derpity doop

    </apex:outputPanel>
</apex:page>

preformatted

3
  • 2
    This is by far the easiest, fastest, and safest way to handle this if there aren't HTML tags like <br> in the data responsible for formatting. Commented Jan 30, 2014 at 19:06
  • 2
    I agree this is a better way. Commented Jan 30, 2014 at 19:45
  • I am using \n inside the chatter post I cant use <br> to do format the post. As you said <br> is working fine inside pdf but doesn't solve the issue with \n Commented Jan 31, 2014 at 7:48
4

You need to use the <br/> tag for line breaks. It just uses standard HTML for that.

If my Visualforce page is:

<apex:page renderAs="PDF">
    Test
    <br/>
    Test
</apex:page>

The page will render as:

Test
Test

If you are generating the String in Apex and displaying it with <apex:outputText>, you will need to explicitly not escape the HTML. To do this, add the escape parameter:

A Boolean value that specifies whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If you do not specify escape="false", the character escape sequence displays as written. Be aware that setting this value to "false" may be a security risk because it allows arbitrary content, including JavaScript, that could be used in a malicious manner.

You code would then look like:

<apex:page renderAs="PDF">
    <apex:outputText value="{!textFromApex}" escape="false"/>
</apex:page>

I don't necessarily recommend this approach however. This opens you up for Cross Site Scripting (XSS).

2
  • The content is coming from chatter poste using connect API so if I put <br> while posting in chatter it <br> is displayed as a text so I cant use this method Commented Jan 30, 2014 at 16:29
  • 1
    This is an escaping issue. I updated the answer. Commented Jan 30, 2014 at 17:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .