I'm trying to show a pdf in android app. The response I get from the server is looking like this. I convert it to input stream and pass it to pdf viewer library
%PDF-1.4 %ÓôÌá 1 0 obj << /CreationDate(D:20180403085232+02'00')
/Creator(PDFsharp 1.32.3057-g (www.pdfsharp.net)) /Producer(PDFsharp
1.32.3057-g (www.pdfsharp.net))
endobj 2 0 obj << /Type/Catalog /Pages 3 0 R
endobj 3 0 obj << /Type/Pages /Count 3 /Kids[4 0 R 8 0 R 11 0 R]
endobj 4 0 obj << /Type/Page /MediaBox[0 0 612 792] /Parent 3 0 R /Contents 5 0 R /Resources << /ProcSet
[/PDF/Text/ImageB/ImageC/ImageI] /XObject << /I0 6 0 R
/ExtGState << /GS0 7 0 R
/Group << /CS/DeviceRGB /S/Transparency /I false /K false
endobj 5 0 obj << /Length 260 /Filter/FlateDecode
stream xœíRMK1½÷Wä˜M“&Mî¢àa]oâIEDF‚¿ÞÌ̺²ø¥”4y¯—´C©#¹ŽÆЃáú!ÏDpñZ†2€š
W9#¾gNŽa“/…à4÷}©gåòŠàf§{¾.«õ–àWìÚ¡WÆT4Bµ
†¡O·e[F>g^í=|UEw‡ª‚Ö$å(U‘ôÇ›„L¶ÜÑ™—~¤6•š'Ú9f”Pz›PŽ€¦¨"бv_gly›Û÷Mä~.î]
™Ûë؈?œå€«Ul¡À™y_6þ»Aÿ—ÿ¤|èYòÿX`ìfÈ»ï³ÉõŠ¹·ò endstream endobj 6 0
obj << /Type/XObject /Subtype/Image /Length 5097196
/Filter/FlateDecode /Width 2511 /Height 3531 /BitsPerComponent 8
/ColorSpace/DeviceRGB /Interpolate true
stream xœìÝ œ¤g]'ðïé9rÂáˆJAE%€ Š"ë‚FQ0 Ë!º» ¢‚+^ (h
This is my code:
// get the response as string
val body = response.body?.string()
// convert it to inputstream
val inputStream = ByteArrayInputStream(body.toByteArray(Charsets.UTF_8))
// load it wil pdf viewer
pdf_viewer.fromStream(inputStream).load()
Everything till the last line is ok. I got init FPDF library but there is nothing on the screen. It stays with white background.
If I open the pdf standalone I can see that everything is fine.
I'm using
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
here is the xml file
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdf_viewer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
EDIT:
the working solution was to get the bytes and pass them to PDFViewer
val bodyBytes: ByteArray = response.body!!.bytes()
runOnUiThread {
pdf_viewer.fromBytes(bodyBytes).enableSwipe(true) // allows to block changing pages using swipe
.swipeHorizontal(false)
.enableDoubletap(true)
.defaultPage(0)
.enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
.password(null)
.scrollHandle(null)
.enableAntialiasing(true) // improve rendering a little bit on low-res screens
// spacing between pages in dp. To define spacing color, set view background
.spacing(0)
.invalidPageColor(Color.WHITE) // color of page that is invalid and cannot be loaded
.load()
}
Related
I have a JAXB REST Web Service getting in request a POST of a JSON and should return a PDF document in response:
#POST
#Path("getReceipt")
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ "application/pdf" })
public Response getReceipt(InputStream incomingData, #Context HttpServletRequest httpRequest) {
...
}
I'm trying to test it with Advanced Rest Client (Google Chrome plugin), which is showing the following as response:
%PDF-1.4
%����
3 0 obj
<</C[0 0 1]/Border[0 0 0]/A<</URI(https://www.totalerg.it/)/S/URI>>/Subtype/Link/Rect[491.43 723.5 557 733.5]>>
endobj
4 0 obj
<</C[0 0 1]/Border[0 0 0]/A<</URI(https://www.totalerg.it/)/S/URI>>/Subtype/Link/Rect[256.65 274.5 322.22 284.5]>>
endobj
5 0 obj
<</Length 993/Filter/FlateDecode>>stream
x��U�n�8}�W�[��Ð����lG�j�릲�}Y0kpaK�,%���s�3vHY����"9�̙G/%>�9��gD������ҙ;�( \|:+WP�h�|D�zo�����)������h�������L2CR��a�%L�
���:��&��g L���1ϲ�Oq���9M�[<�-�ǹ����r���
wL�2�:W�m#��J��\*��":��Ld7�]
�3�6�E��Kn_<�}�;���,��g�����uk��D^O��6~��Y����]�=1ٸ�gq:���v�l��"��o��x��ǔ�a�09�3H���VeSY?��,�A����l��^*(��W�BE#J�PKX��Fк�s�^��
�H�)��� ��V��
�k<���FntUj<��!F�/
���U#dU#�q�]ZzUnd�I��Z�w�w'��%��l�4�^!G���~��Ƅ�n��̯�?Ԫ,&�U�1teT"u^���r�P�Bw�:YkLX_:�������ī��Mw��P"���\!%���7����zWO}Yp���h�8�����n�]�� ;x�o�2w�38�ś.��/�~�+e"pC����ڳk�]�c#
�����E�{�}�nZ��8�35T�IC+��6�6����E���">J��AZ���F��#��j*����*7�#Pm]����e�e���U�,�؍�!�j�Z��B�de�ҿ�������A֍i����`\T0�0r������Ȇ �G#A��������϶��f���'���͵�,6c�.�4�O�Y:6C.6�}�!]éy�{E߱?��>�<Ƭ�u�y$��9��L���f�]�T��ܸ�/w���������^qj[�r��U)g1b������W���Ǥ�*1�؆�������Ȁ8�F�c�ٯB^�bk�n=�?u��x�;�]�H0rsg���tI[x�����G�0�����#p�EW��B�������L�
endstream
endobj
7 0 obj
<</Parent 6 0 R/Contents 5 0 R/Type/Page/Resources<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]/Font<</F1 1 0 R/F2 2 0 R>>>>/MediaBox[0 0 595 842]/Annots[3 0 R 4 0 R]>>
endobj
1 0 obj
<</BaseFont/Helvetica/Type/Font/Encoding/WinAnsiEncoding/Subtype/Type1>>
endobj
2 0 obj
<</BaseFont/Helvetica-Bold/Type/Font/Encoding/WinAnsiEncoding/Subtype/Type1>>
endobj
6 0 obj
<</ITXT(2.1.7)/Type/Pages/Count 1/Kids[7 0 R]>>
endobj
8 0 obj
<</Type/Catalog/Pages 6 0 R>>
endobj
9 0 obj
<</Producer(iText 2.1.7 by 1T3XT)/ModDate(D:20150907102806+02'00')/CreationDate(D:20150907102806+02'00')>>
endobj
xref
0 10
0000000000 65535 f
0000001518 00000 n
0000001606 00000 n
0000000015 00000 n
0000000142 00000 n
0000000272 00000 n
0000001699 00000 n
0000001332 00000 n
0000001762 00000 n
0000001807 00000 n
trailer
<</Root 8 0 R/ID [<f16ea10e09183af8aff079f97cfac53f><fe60918ac5b80276ed8a082dedebf230>]/Info 9 0 R/Size 10>>
startxref
1929
%%EOF
This text version of binary file is different (more question marked characters in place of other ones) from the one I can see opening the binary file from file system with a text editor.
My question is: how could I test this service posting the JSON request and being able to open PDF document in the response? Should I use another tool, or build a form?
The "Save response" button help you save your response to a file :
You just need to return the pdf byte array using the proper media type and the browser will do the rest. ie:
#POST
#Path("getReceipt")
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ "application/pdf" })
public byte[] getReceipt(InputStream incomingData) {
return your_pdf_byte_array;
}
And to open the PDF document use postman chrome extension
I want to read binary data from file and send it to remote Java App.
As I found here:
I can get it like this (part of my code):
else
{
$fp = fopen("binary file","rb");
$vector="";
while (!feof($fp)) {
// Read the file, in chunks of 16 byte
$data = fread($fp,16);
$arr = unpack("C*",$data);
foreach ($arr as $key => $value) {
$vector.=" ".$value;
}
$vector.="\n";
}
}
I send some headers
header("Content-Type: multipart/related; boundary=bounary----I don't know if boundary value is private".$eol);
header("MIME-Version: 1.0".$eol);
header("Connection: Keep-Alive".$eol);
header("Accept-Encoding: gzip, deflate".$eol);
header("Host: host".$eol.$eol);
header("Content-Type: multipart/related; boundary=bounary----I don't know if boundary value is private".$eol);
header("Content-Type: multipart/related; boundary=bounary----I don't know if boundary value is private".$eol);
Then I print it like this:
echo "--".$BOUNDARY.$eol;
echo "Content-Type: application/octet-stream".$eol;
echo "Content-Length: ".strlen($vector).$eol;
echo "Content-Transfer-Encoding: binary".$eol;
echo $eol.$vector.$eol;
echo "--".$BOUNDARY."--".$eol;
I test it in Advanced Rest Client Application and see binary data:
0 0 0 72 0 54 0 55 0 97 0 56 0 51 0 49
0 101 0 56 0 45 0 53 0 102 0 48 0 56 0 45
0 52 0 100 0 49 0 99 0 45 0 97 0 57 0 57
0 52 0 45 0 101 0 101 0 53 0 97 0 51 0 52
0 49 0 52 0 50 0 54 0 57 0 51 0 0 0 1
0 0 0 0 4 0 0 1 0 0 0 0 1 0 0 0...
But Java coder sayas that there is an empty string instead of binary data? How can I echo this binary data in proper way? What can cause this problem?
Update: We've found, that no matter what Content-Length header I set, in his app he receives header: Content-Length: 475
However in Advanced Rest Client I see my value of content-length. Well it can cause the problem. Can it be caused by php somehow?
Perhaps the 2 $eol's in this line is causing the subsequent headers to not be sent:
header("Host: host".$eol.$eol);
Try changing it to 1, or in fact I doubt you even need the EOL char in the string you send to header().
Getting below Exception while trying to read byte array using iText PdfReader,
Below is my code, I'm able to open this file in Acrobat reader
PdfReader reader = new PdfReader(bFile);
Exception:
java.lang.ClassCastException: com.itextpdf.text.pdf.PdfNull cannot be cast to com.itextpdf.text.pdf.PdfDictionary
at com.itextpdf.text.pdf.PdfReader$PageRefs.iteratePages(PdfReader.java:3712)
at com.itextpdf.text.pdf.PdfReader$PageRefs.iteratePages(PdfReader.java:3743)
at com.itextpdf.text.pdf.PdfReader$PageRefs.readPages(PdfReader.java:3548)
at com.itextpdf.text.pdf.PdfReader$PageRefs.<init>(PdfReader.java:3518)
at com.itextpdf.text.pdf.PdfReader$PageRefs.<init>(PdfReader.java:3496)
at com.itextpdf.text.pdf.PdfReader.readPages(PdfReader.java:1142)
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:659)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:176)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:244)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:234)
Im using iText 5.4.4, I couldn't find much details in googling. It looks PDF has some issues, couldn't get whats the issue. Below is the excerpts from PDF
%PDF-1.5
%âãÏÓ
1 0 obj
<<
/Type /Catalog
/Lang (en-US)
/StructTreeRoot 39 0 R
/MarkInfo <<
/Marked true
>>
/Pages 187 0 R
/AcroForm 350 0 R
/OCProperties 2131 0 R
/Outlines 2531 0 R
/OpenAction <<
/Type /Action
/S /GoTo
/D [ 3 0 R /XYZ 0 792 0 ]
>>
/ViewerPreferences <<
/HideToolbar false
/HideMenubar false
/HideWindowUI false
/FitWindow false
/CenterWindow false
>>
UPDATE: After debugging I found that /Pages 187 0 R is the problem. If I change to /Pages 2 0 R then it works. Could some please help me what does that /Pages refers ?
I am student of Computer engineering dept of YeungNam University in Korea.
First, sorry about my poor english skill.
I need help, please.
I found USB API for Java.
I need USB device's PID, VID and unique serial number because I need to do identify each USB device for my project(just mass storage device).
I use below example code.
(This is usb4java API example code.)
This code show me some information about USB HUDs, connected devices.
package org.usb4java.javax.examples;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbEndpoint;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbPort;
import javax.usb.UsbServices;
/**
* Dumps all devices by using the javax-usb API.
*
* #author Klaus Reimer <k#ailis.de>
*/
public class DumpDevices
{
/**
* Dumps the specified USB device to stdout.
*
* #param device
* The USB device to dump.
*/
private static void dumpDevice(final UsbDevice device)
{
// Dump information about the device itself
System.out.println(device);
final UsbPort port = device.getParentUsbPort();
if (port != null)
{
System.out.println("Connected to port: " + port.getPortNumber());
System.out.println("Parent: " + port.getUsbHub());
}
// Dump device descriptor
System.out.println(device.getUsbDeviceDescriptor());
// Process all configurations
for (UsbConfiguration configuration: (List<UsbConfiguration>) device
.getUsbConfigurations())
{
// Dump configuration descriptor
System.out.println(configuration.getUsbConfigurationDescriptor());
// Process all interfaces
for (UsbInterface iface: (List<UsbInterface>) configuration
.getUsbInterfaces())
{
// Dump the interface descriptor
System.out.println(iface.getUsbInterfaceDescriptor());
// Process all endpoints
for (UsbEndpoint endpoint: (List<UsbEndpoint>) iface
.getUsbEndpoints())
{
// Dump the endpoint descriptor
System.out.println(endpoint.getUsbEndpointDescriptor());
}
}
}
System.out.println();
// Dump child devices if device is a hub
if (device.isUsbHub())
{
final UsbHub hub = (UsbHub) device;
for (UsbDevice child: (List<UsbDevice>) hub.getAttachedUsbDevices())
{
dumpDevice(child);
}
}
}
/**
* Main method.
*
* #param args
* Command-line arguments (Ignored)
* #throws UsbException
* When an USB error was reported which wasn't handled by this
* program itself.
*/
public static void main(final String[] args) throws UsbException
{
// Get the USB services and dump information about them
final UsbServices services = UsbHostManager.getUsbServices();
System.out.println("USB Service Implementation: "
+ services.getImpDescription());
System.out.println("Implementation version: "
+ services.getImpVersion());
System.out.println("Service API version: " + services.getApiVersion());
System.out.println();
// Dump the root USB hub
dumpDevice(services.getRootUsbHub());
}
}
and this code result like this:
USB Service Implementation: usb4java
Implementation version: 1.2.0
Service API version: 1.0.2
usb4java root hub 1.0.0
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 1.01
bDeviceClass 9 Hub
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 8
idVendor 0xffff
idProduct 0xffff
bcdDevice 0.00
iManufacturer 1
iProduct 2
iSerial 3
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 18
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0x80
(Bus Powered)
bMaxPower 0mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 9 Hub
bInterfaceSubClass 0
bInterfaceProtocol 0
iInterface 0
Bus 002 Device 007: ID 203a:fffa
Connected to port: 1
Parent: usb4java root hub 1.0.0
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 0 Per Interface
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 64
idVendor 0x203a
idProduct 0xfffa
bcdDevice 1.00
iManufacturer 1
iProduct 2
iSerial 3
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 25
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 1
bmAttributes 0xc0
Self Powered
bMaxPower 0mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 7 Printer
bInterfaceSubClass 1
bInterfaceProtocol 1
iInterface 4
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x01 EP 1 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 512
bInterval 0
.
.
.
.
Bus 002 Device 003: ID 152d:2329
Connected to port: 3
Parent: usb4java root hub 1.0.0
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 0 Per Interface
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 64
idVendor 0x152d
idProduct 0x2329
bcdDevice 1.00
iManufacturer 1
iProduct 2
iSerial 5
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 32
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 4
bmAttributes 0xc0
Self Powered
bMaxPower 2mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 2
bInterfaceClass 8 Mass Storage
bInterfaceSubClass 6
bInterfaceProtocol 80
iInterface 6
.
.
.
.
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x02 EP 2 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 512
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 512
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x01 EP 1 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 512
bInterval 0
In result of code, there is mass storage and I can see PID and VID, but there is iserialnumber(index of serial number in device descriptor) instead of real serialnumber.
I think that to identify each USB mass storage device, need combination of PID, VID, S/N.
How can I get serial number?
In Usb4Java, Javax.usb, libusb, these APIs not include methods like 'getSerialnumber()'.
Help me please.
The "iSerial" is the index of the version string in the device's string table. You can retrieve the corresponding string using the getString(byte) method on the device. Same thing goes for "iManufacturer" and "iProduct".
Keep in mind that not all devices will have a unique serial number.
I am working on converting a pdf file to tiff images for faxing in java.Pika applications are responsible to process and send created tiff file.Everything is fine,tiff file is created with the tags.But Pika is not sending tiff file.It gives an error about unsupported file format.Pika error message is below
-- (PK_STATUS PKH_ERROR_FAX_UNSUPPORTED_FILE_FORMAT)
What is the problem,what i am missing,someone can help ? Tiff tag data
SubFileType (1 Long): Page
ImageWidth (1 Long): 1728
ImageLength (1 Long): 2297
BitsPerSample (1 Short): 1
Compression (1 Short): Group 4 Fax (aka CCITT FAX4)
Photometric (1 Short): MinIsWhite
FillOrder (1 Short): Lsb2Msb
StripOffsets (288 Long): 2625, 2629, 2633, 2637, 2641, 2645, 2649,...
SamplesPerPixel (1 Short): 1
RowsPerStrip (1 Long): 8
StripByteCounts (288 Long): 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,...
XResolution (1 Rational): 204
YResolution (1 Rational): 196
Group4Options (1 Long): 0
ResolutionUnit (1 Short): Inch
PageNumber (2 Short): 0, 1
Software (19 ASCII): DDoc2TiffConverter
DateTime (20 ASCII): 2013:09:08 23:35:17
BadFaxLines (1 Long): 0
CleanFaxData (1 Short): 0
ConsecutiveBadFaxLines (1 Long): 0
Solved problem.It was related with the strip count of the tiff image.Converted from multi-strip to single strip and then it was successful to send tiff via fax.To be informative i will share how tiff was converted from multi to single strip.
TIFFEncodeParam param = new TIFFEncodeParam();
param.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4);
param.setReverseFillOrder(true);
param.setLittleEndian(true);
param.setWriteTiled(false);
param.setTileSize(-1, images[0].getHeight());
param.setTileSize(-1, images[0].getHeight()); This part sets to the single strip.