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?

10

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. – ca_peterson Jan 30 '14 at 19:06
  • 2
    I agree this is a better way. – Jesse Altman Jan 30 '14 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 – Shebin Mathew Jan 31 '14 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 – Shebin Mathew Jan 30 '14 at 16:29
  • 1
    This is an escaping issue. I updated the answer. – Jesse Altman Jan 30 '14 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.