Preserving CRLF characters when rendering an ERB file - ruby-on-rails-3

I'm trying to render an ERB file through Passenger which is saved with DOS-style CRLF line breaks, but the line breaks are getting converted to just LF. Is there an option one can pass to the 'render' method that forces ERB to preserve CRLF line breaks? I'm currently using "render(:content_type => 'text/plain', :layout => false)" but that is not doing the trick.

Related

Passbook: line breaks in PKBarcodeFormatQR

I'm trying to build a wallet card included a VCF contact in the QR Code.
I got an issue with the line breaks, that are mandatory in VCF contact format.
I included my VCF String like this (build in PHP):
'barcodes' => [
0 => [
'format' => 'PKBarcodeFormatQR',
'message' => "$vCard",
'messageEncoding' => 'iso-8859-1',
],
],
And the generated QRCode included this string:
BEGIN:VCARD\nVERSION:3.0\nREV:2022-09-16T16:29:50Z\nN;CHARSET=utf-8:[...]END:VCARD\n
As you cas see, there is some \n instead of line breaks.
I need something like this:
BEGIN:VCARD
VERSION:3.0
REV:2022-09-16T16:29:50Z
N;CHARSET=utf-8:[...]
END:VCARD
Do you know how I can replace all \n with line breaks ?
Note: Everything working fine since iOS 16. I don't know what Apple changed in Wallet...

How to display PDF file on yii2

I have a audit table and audit_report field.Field type is text .I saved pdf files into folder and saved name to database.I tried to display the pdf on view page. but the box with image sign only getting. I could display jpeg and png files nicely.How to display PDF on view page of yii2 framework.
This would work,
return Yii::$app->response->sendFile($completePath, $filename, ['inline'=>true]);
Input the function with third param as array of value 'inline'=>true to open the file within the browser window.
See the documentation here sendFile()
You could add a button that opens the file in a new tab, but make it link to an action in your controller that returns the file instead of the direct path to the file:
In your view:
<?= Html::a('PDF', [
'controller/pdf',
'id' => $model->id,
], [
'class' => 'btn btn-primary',
'target' => '_blank',
]); ?>
In your controller:
public function actionPdf($id) {
$model = ModelClass::findOne($id);
// This will need to be the path relative to the root of your app.
$filePath = '/your/file/path';
// Might need to change '#app' for another alias
$completePath = Yii::getAlias('#app'.$filePath.'/'.$model->fileName);
return Yii::$app->response->sendFile($completePath, $model->fileName);
}
Aliases - Key Concepts - The Definitive Guide to Yii 2.0
Although the question has been answered there is one thing that needs to be addressed if you have the file content/stream instead of the file path, like for instance you are using Dropbox API and you receive a stream from the API and want to display that file instead of forcing the browser to download.
For this case you can use the sendContentAsFile when attempting to display the PDF file in the browser you will need to specify the mimeType option too along with the "inline"=>true because the default mimeType value is set to application/octet-stream which is used to download a file and to display inline in browser you need to change it to application/pdf.
return Yii::$app->response->sendContentAsFile(
$fileContent,
$filename,
['inline' => true, 'mimeType' => 'application/pdf']
);

Wicked PDF, generating PDF from database table- images and style issues

I have an uploader (internal use only) that will upload an HTML document to a binary column of a table in my client-facing website. The client facing site has an index that allows the user to view the page as a normal website (using send_data h_t.html_code, :type => "html", :disposition => "inline"). I also want to give the user the ability to download a PDF of the page. For that I'm using wicked_pdf.
The entire problem seems to stem from the fact that the data is stored in the database. As strange as it sounds, it is vital to business operations that I get formatting exact. The issue is I can't see any image, and the stylesheets/style tags don't have any effect.
What I've tried-
Gsub-
def show
html = HtmlTranscript.find(params[:id])
html_code = html.html_code.gsub('<img src="/images/bwTranscriptLogo.gif" alt="Logo">','<%= wicked_pdf_image_tag "bwTranscriptLogo.gif" %>')
html_code = html_code.gsub('<link rel="StyleSheet" href="" type="text/css">','<%= wicked_pdf_stylesheet_link_tag "transcripts.css" %>')
transcript = WickedPdf.new.pdf_from_string(html_code)
respond_to do |format|
format.html do
send_data transcript, :type => "pdf", :disposition => "attachment"
end
##### i never could get this part figured out, so if you have a fix for this...
# format.pdf do
# render :pdf => "transcript_for_#{#html.created_at}", :template => "html_transcripts/show.html.erb", :layout => false
# end
end
end
Using a template-
#Controller (above, modified)
html = HtmlTranscript.find(params[:id])
#html_code = html.html_code.gsub('<img src="/images/bwTranscriptLogo.gif" alt="Logo">','<%= wicked_pdf_image_tag "bwTranscriptLogo.gif" %>')
#html_code = #html_code.gsub('<link rel="StyleSheet" href="" type="text/css">','<%= wicked_pdf_stylesheet_link_tag "transcripts.css" %>')
transcript = WickedPdf.new.pdf_from_string(render_to_string(:template => "html_transcripts/show.html.erb", :layout => false))
#view
<!-- tried with stylesheet & image link tags, with wicked_pdf stylesheet & image link tags, with html style & img tags, etc -->
<%= raw(#html_code) %>
And both will generate a transcript- but neither will have style OR image.
Creating an initializer-
module WickedPdfHelper
def wicked_pdf_stylesheet_link_tag(*sources)
sources.collect { |source|
"<style type='text/css'>#{Rails.application.assets.find_asset("#{source}.css")}</style>"
}.join("\n").gsub(/url\(['"](.+)['"]\)(.+)/,%[url("#{wicked_pdf_image_location("\\1")}")\\2]).html_safe
end
def wicked_pdf_image_tag(img, options={})
image_tag wicked_pdf_image_location(img), options
end
def wicked_pdf_image_location(img)
"file://#{Rails.root.join('app', 'assets', 'images', img)}"
end
def wicked_pdf_javascript_src_tag(source)
"<script type='text/javascript'>#{Rails.application.assets.find_asset("#{source}.js").body}</script>"
end
def wicked_pdf_javascript_include_tag(*sources)
sources.collect{ |source| wicked_pdf_javascript_src_tag(source) }.join("\n").html_safe
end
end
did absolutely nothing, and I have no idea what to try next.
As a side note, the code to view the HTML version of the transcript is as follows:
def transcript_data
h_t = HtmlTranscript.find(params[:id])
send_data h_t.html_code, :type => "html", :disposition => "inline"
end
It requires no view, as the html data is stored in the database, but I get image, style, etc. Everything works with the HTML version- just not the PDF.
I'm on ruby 1.8.7 with rails 3.0.20.
Solved-
As it turns out, there was more than one issue at hand.
1- Installation of wkhtmltopdf for Ubuntu via $apt-get install does not quite do the trick for what I wanted...
see http://rubykitchen.in/blog/2013/03/17/pdf-generation-with-rails
(there may have also been an issue with having not previously run sudo apt-get install openssl build-essential xorg libssl-dev libxrender-dev, as when I did, it installed a number of components I did not previously have.)
2- The HTML files I had uploaded contained image & style code that was breaking the formatting. I fixed it with this...
def rm_by_line(which = 0, line1 = 0, line2 = 0)
h_t = HtmlTranscript.find(which)
line_by_line = h_t.html_code.split('
')
for i in line1..line2
line_by_line[i] = ''
end
line_by_line = line_by_line.join('
').strip
return line_by_line
end
Then, all I had to do was pass which lines I wanted to remove.
(I had to split the parens with a carriage return because '\n' didn't function properly when calling 'raw' on the returned string.)
3- wicked_pdf_stylesheet_link_tag and wicked_pdf_image_tag were undefined. I had to inline the style formatting I wanted into a layout I created (turns out wicked_pdf_stylesheet_link_tag used asset pipeline wich my ruby/rails did not implement, which also means I had to get rid of the javascript helpers) and created a helper for wicked_pdf_image_tag, making a switch in the layout for which image tag (image_tag or wicked_pdf_image_tag) to be used.
4- I needed both a .html.erb & a .pdf.erb for my templates, so I made both.
5- Got rid of WickedPdf.new.pdf_from_string in favor of linking to either html or pdf by using :format => 'html' or :format => 'pdf' in the link_to tag.

Rails 3.2: Error emptly file upload result

I'm trying to use the jquery file upload plugin in my rails app to upload images, documents, and pdfs. I changed the accepted file types to accept pdfs etc. However, when I click 'Start upload', I get the following error (only with .pdf, .docx, and .doc):
Error emptly file upload result
If I try to upload a .txt, .png, .jpg, or .gif, it works fine. I tried increasing the max file size and also creating a .pdf file with 1 word and still got the same error. I've been searching online, I've mostly seen people suggest using the gd-extension for php, but I have a rails application so is there a rails alternative for gd-extension?
Thanks
Fixed! For anyone with the same issue this is what I did:
This fix is for Paperclip fyi.
So in the model where you have 'has_attached_file', you need to pass an additional attribute here: :whiny => false, so it should look something like:
has_attached_file :asset,
:styles => { :thumb => "100x100>" },
:whiny => false,
:storage => :s3,
:s3_credentials => "config/s3.yml",
:path => ":id/:style/:filename"
":whiny" is set to true by default, and it essentially raises an error if Paperclip cannot process a thumbnail of the uploaded file, and since pdf, doc, etc.. doesn't have a thumbnail the emptyResult error was being raised.
Sources:
Paperclip::NotIdentifiedByImageMagickError when file is not a valid attachment content type
https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip.rb

Can I render a text string as a partial in Rails 3?

I am storing customer-specific partials on S3. When I render the value of the S3 object, it renders as text. How can I render it so that it appears within my main layout?
Looks like I just need to:
render :text => myTextFromS3, :layout => true
And it works!
Update: Since 2013 rails changed
There is 3 different ways:
render html: '<strong>HTML String</strong>' # render with `text/html` MIME type
render plain: 'plain text' # render with `text/plain` MIME type
render body: 'raw body' # render raw content, does not set content type, inherits
# default content type, which currently is `text/html`
Source https://github.com/rails/rails/issues/12374