mPDF error on Codeigniter - html

I tried to convert a html page to pdf and was decided to use mPDF, I follow what the documentation does. When running the code, it does not prompt out the PDF to ask for save. Btw I get those error code.
Here is the code from Controller.
//this data will be passed on to the view
$data['the_content']='mPDF and CodeIgniter are cool!';
//load the view, pass the variable and do not show it but "save" the output into $html variable
$html=$this->load->view('ajax/pdf_output', $data, true);
//this the the PDF filename that user will get to download
$pdfFilePath = "the_pdf_output.pdf";
//load mPDF library
$this->load->library('m_pdf');
//actually, you can pass mPDF parameter on this load() function
$pdf = $this->m_pdf->load();
//generate the PDF!
$pdf->WriteHTML($html);
//offer it to user via browser download! (The PDF won't be saved on your server HDD)
$pdf->Output($pdfFilePath, "I");
Below is the result i get:
%PDF-1.4 %���� 3 0 obj <> /Contents 4 0 R>> endobj 4 0 obj <> stream x��P]O�#���㓚����^�1�h�7�C��B(h���sW�Fs����vvv�B')�ձCgha�6��Mp�6� �H�U[P��{��-[�uz��#��뮉�r�#Υ�9�R���'�J�h&���e� �J�YW�f����\���/�m�Ӷ�����J.w���j��N�ގ��^�=f!��ƲO����o�92yh�m���9� �e��[��#�3���?u�R%_�¿�)�X|jt2H׆��+��S��™9%�R��:��ƒ7��m��Z����9n� endstream endobj 1 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj 7 0 obj <> endobj 8 0 obj <> stream /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo <> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0000> <0000> endbfrange endcmap CMapName currentdict /CMap defineresource pop end end endstream endobj 9 0 obj <> endobj 10 0 obj < >> /FontFile2 12 0 R >> endobj 11 0 obj <> stream x����V�����Qfd%{dT*�l-�Ȉ��_����s��ڥ����}��#;���t���:��Nt�S�n�3�m�s��B��h��JW���nt�[��Nw�^�{��&�l�GM7�l�{���z��^4��^��7��]���B�-��J���V[�K�}�[}�G?��f���V���n���w�� endstream endobj 12 0 obj <> stream x��| \TU��9��;�.�zqIe�]ce�t��apfQQ�q�qGKSS+5-K+Ӟ�z�6�35���gi���wν3d=��}����g�s�=������\0�B��4#+76�r����=\��}�O��:�p <7�r���G~BHH���EŖ�j��B�C_U��W /� q<��U�}��<�!��t�Qo��ۀPdwXN���<���X���<�~]��Po3oC(��_��gW��Ўz��r��8�XR!<����+�vG�B4�Q��� ����Z�<���(��^�Dhk��#��r'WQ����h4�F��i�Fw���H$�]�3�$77kBi(��e��A�=7�"凨����C���]D��.=�onf�577���l��$��y#����? ��CA(�G!(���#��:�Ѓ��uE݀�p�"Qw�z�����F}P4��bP,����8�EP<���h����h�yQJF)H�R�(4��1h,JG(e�l4��\��ƣ|4MD�#�S�T4 =���H:�Ev$���-�|�tdF3�r��w�\�����>�����~�N��0OZ�ˀ���;0����>�H����m� $Z�|�^t�E��r�Uo�l/�ì-���a^� �$#�΢O�b�A5h ��L�]��tx1�� ��$d�Y�Y�� Jf��,��W�qo�Cf�"<$�a2z�"�8>=�'�˧� s��*/z[�*�{��#��x���op:.��O�A{�?p�Yz����������-ޡ��!y�� }kP&� T�]��H"0���� Qi�c �&�oL ���Q򒏡�c���������Ҥc�C�H��11*�� ��=6{�|��.EE��H��܉�dO� �����[ ,~O�5�֓��І,>�lozG��s�� ���6Mo��^�m���� 0P�!,T�#DK�"�����SS�ku��#�%�33�̐�hz��I�z�v�zNG��`���N���"�a�[
Anyone can tell me what happening with this?

it looks like the "I" parameter is causing trouble because the browser doesn't recognize your file
according to the docu you've the following Possibilities:
I: send the file inline to the browser. The plug-in is used if available. The name given by $filename is used when one selects the “Save as” option on the link generating the PDF.
D: send to the browser and force a file download with the name given by $filename.
F: save to a local file with the name given by $filename (may include a path).
S: return the document as a string. $filename is ignored.
try something like that :
$pdf->Output($pdfFilePath, "D");
die;
or on the other hand you can try to add some header to tell the browser explicitly this is a pdf document
header('Content-Type: application/pdf');
$pdf->Output($pdfFilePath, "I");
die;
because it could be CIs outpout class overwrites MPDF's header (but this is just a hunch)

$html=$this->load->view("ajax/pdf_output",$data,true);
//load mPDF library
$this->load->library('m_pdf');
//generate the PDF from the given html
$this->m_pdf->pdf->WriteHTML($html);
//download it.
ob_clean();
$this->m_pdf->pdf->Output($pdfFilePath,'F');
check your folder.....

If you want show download dialogue your need to place below code
$filename = time()."_order.pdf"; //your file name
$html = $this->load->view('unpaid_voucher2',$data,true);
/// $data variable is your dynamic data if you have no dynmic data then you can pass empty instead of variable like.
$html = $this->load->view('unpaid_voucher2','',true);
$this->load->library('M_pdf');
$this->m_pdf->pdf->WriteHTML($html);
//For download pass D and save on server pass F.
$this->m_pdf->pdf->Output("./uploads/".$filename, "D");
Here is full configuration to integrate mpdf into codeigniter

The string is a binary PDF representation and its presence means Content-type: application/pdf header is not sent correctly or it is
overriden by your code or setup. Most likely by text/plain or text/html.
Try to figure out these:
Are you resetting Content-type header in PHP code somewhere after calling the mPDF Output method?
Is your server forcing a different Content-type somewhere in your setup?
Does your browser support displaying application/pdf Content-type directly?
Given that the D Output mode gives you the same result, I'd guess the Content-type header is being overriden somewhere after calling the Output method, presumably by CodeIgniter.

Related

Python format issue with sending and receiving a file

I am sending a JSON file from the cloud to a device using Azure IoT cloud-to-device messages via the Python SDKs.
The file contains lots of new lines and tabs which I would like to preserve. The file received of course must be in the exact same format as the one being sent.
This is on the sending end (cloud) :
FILENAME = "my_file.json"
f = open (FILENAME, "r")
data = f.read()
registry_manager.send_c2d_message(DEVICE_ID, data)
And on the receiving end (device) :
message = client.receive_message()
received_file = open("output.json", "w")
received_file.write(str(message))
received_file.close()
However the file contains just one line with the special characters b' \n \t , and not the actual tabs and new lines etc. Here is just the beginning of it :
b'{\n "group1":\n [\n {\n
How should I get this to format properly and not print the special characters, but instead lines and tabs etc.? Thanks in advance.

Migrated from TCL8.4 to 8.5 and Im facing issues with the file sourcing

My application runs well on RHEL 5 (TCL 8.4). But in RHEL 7 64bit TCL8.5, the database files are not sourced in correctly. The application is by default pointing to the last record file in the db. Hence, im assuming it might be issue with the way 8.5 handles the file sourcing. So i created a file X and wrote the below code. (Please ignore dbname and /path, it works fine)
File X
#!/bin/sh
# \
exec tclsh "$0" "$#"
puts [package require Itcl]
namespace import ::itcl::*
puts $itcl::patchLevel
puts $itcl::library
set databases /dbname
set system ($databases,dbpath) /path
source File.class.tcl
source FareFile.class.tcl
puts [Fare.File formtitle]
source Record1File.class.tcl
puts [Fare.File formtitle]
I source FareFile in and print the form title(o/p: Fare Viewer) using the formtitle method which is declared in the File.class.tcl. And then I source Record1File and print the FareFile formtitle (the first one), its printing the form title of Record1File. The formtitle method is returning the value of the lastest sourced file. This does not happen in 8.4
File.class.tcl:
class File {
variable fileinfo
variable recordarray
variable allads_flag 0
variable updates_is_lastkey 0
method formtitle {} {
variable fileinfo
return $fileinfo(formtitle)
}
}
FareFile.class.tcl
FareFile ::Fare.File
::Fare.File parse_fields {
tabtitle "Fares"
formtitle "Fare Viewer"
}
Record1File.class.tcl
Record1File ::Record1.File
::Record1.File parse_fields {
tabtitle "Record 1"
formtitle "Record 1 Viewer"
output in 8.4 / RHEL 5: (Expected output in 8.5)
3.4
3.4.0
/path
Fare Viewer
Fare Viewer
output in 8.5 / RHEL 7:
3.4
3.4.3
/path
Fare Viewer
Record 1 Viewer
If you see the output on both platforms, its different. Please help
(This is only a tentative answer, given all the blanks of the question, but I need the formatting capabilities:)
Try the following pls., by rewriting the body script of method formtitle as follows:
class File {
method formtitle {} {
set v variable
$v fileinfo
return $fileinfo(formtitle)
}
}
... and report back by posting a comment.

Cannot send base64 String to PubNub

I am using PyCamera module of Raspberry Pi to capture an image and store as .jpg.
first encoding the image using base64.encodestring(). but while sending encoded string to PubNub server, I get error on my_publish_callback as
('ERROR: ', 'Expecting value: line 1 column 1 (char 0)')
('ERROR: ', JSONDecodeError('Expecting value: line 1 column 1 (char 0)',))
I have tried using base64.b64encode() but still get the same errors. I have tried the script in python 2 and 3;
def my_publish_callback(envelope, status):
if not status.is_error():
pass # Message successfully published to specified channel.
else:
#print("recv: ", envelope)
print("ERROR: ", status.error_data.information)
print("ERROR: ", status.error_data.exception)
def publish(channel, msg):
pubnub.publish().channel(channel).message(msg).async(my_publish_callback)
def captureAndSendImage():
camera.start_preview()
time.sleep(2)
camera.capture("/home/pi/Desktop/image.jpg")
camera.stop_preview()
with open("/home/pi/Desktop/image.jpg", "rb") as f:
encoded = base64.encodestring(f.read())
publish(myChannel, str(encoded))
I am not able to find or print full error traceback so that I can get some more clues about where the error is occurring. But it looks like PubNub is trying to parse the data in JSON, and its failing.
I realized the .jpg file size is 154KB, whereas PubNub max packet size is 32KB, so that should clearly say it all. PubNub recommends to send large messages by splitting them and re-arranging them in subscriber-end. Thanks #Craig for referring to that link, Its useful though support.pubnub.com/support/discussions/topics/14000006326

Ruby: Handling different JSON response that is not what is expected

Searched online and read through the documents, but have not been able to find an answer. I am fairly new and part of learning Ruby I wanted to make the script below.
The Script essentially does a Carrier Lookup on a list of numbers that are provided through a CSV file. The CSV file has just one row with the column header "number".
Everything runs fine UNTIL the API gives me an output that is different from the others. In this example, it tells me that one of the numbers in my file is not a valid US number. This then causes my script to stop running.
I am looking to see if there is a way to either ignore it (I read about Begin and End, but was not able to get it to work) or ideally either create a separate file with those errors or just put the data into the main file.
Any help would be much appreciated. Thank you.
Ruby Code:
require 'csv'
require 'uri'
require 'net/http'
require 'json'
number = 0
CSV.foreach('data1.csv',headers: true) do |row|
number = row['number'].to_i
uri = URI("https://api.message360.com/api/v3/carrier/lookup.json?PhoneNumber=#{number}")
req = Net::HTTP::Post.new(uri)
req.basic_auth 'XXX' , 'XXX'
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) {|http|
http.request(req)
}
json = JSON.parse(res.body)
new = json["Message360"]["Carrier"].values
CSV.open("new.csv", "ab") do |csv|
csv << new
end
end
File Data:
number
5556667777
9998887777
Good Response example in JSON:
{"Message360"=>{"ResponseStatus"=>1, "Carrier"=>{"ApiVersion"=>"3", "CarrierSid"=>"XXX", "AccountSid"=>"XXX", "PhoneNumber"=>"+19495554444", "Network"=>"Cellco Partnership dba Verizon Wireless - CA", "Wireless"=>"true", "ZipCode"=>"92604", "City"=>"Irvine", "Price"=>0.0003, "Status"=>"success", "DateCreated"=>"2018-05-15 23:05:15"}}}
The response that causes Script to stop:
{
"Message360": {
"ResponseStatus": 0,
"Errors": {
"Error": [
{
"Code": "ER-M360-CAR-111",
"Message": "Allowed Only Valid E164 North American Numbers.",
"MoreInfo": []
}
]
}
}
}
It would appear you can just check json["Message360"]["ResponseStatus"] first for a 0 or 1 to indicate failure or success.
I'd probably add a rescue to help catch any other errors (malformed JSON, network issue, etc.)
CSV.foreach('data1.csv',headers: true) do |row|
number = row['number'].to_i
...
json = JSON.parse(res.body)
if json["Message360"]["ResponseStatus"] == 1
new = json["Message360"]["Carrier"].values
CSV.open("new.csv", "ab") do |csv|
csv << new
end
else
# handle bad response
end
rescue StandardError => e
# request failed for some reason, log e and the number?
end

Parse txt file with shell

I have a txt file containing the output from several commands executed on a networking equipment. I wanted to parse this txt file so i can sort and print on an HTML page.
What is the best/easiest way to do this? Export every command to an array and then print array with sort on the HTML code?
Commands are between lines and they're tabular data. example:
*********************************************************************
# command 1
*********************************************************************
Object column1 column2 Total
-------------------------------------------------------------------
object 1 526 9484 10010
object 2 2 10008 10010
Object 3 0 20000 20000
*********************************************************************
# command 2
*********************************************************************
(... tabular data ...)
Can someone suggest any code or file where see how to make this work?
Thanks!
This can be easily done in Python with this example code:
f = open('input.txt')
rulers = 0
table = []
for line in f.readlines():
if '****' in line:
rulers += 1
if rulers == 2:
table = []
elif rulers > 2:
print(table)
rulers = 0
continue
if line == '\n' or '----' in line or line.startswith('#'):
continue
table.append(line.split())
print(table)
It just prints list of lists of the tabular values. But it can be formatted to whatever HTML or another format you need.
Import into your spreadsheet software. Export to HTML from there, and modify as needed.