obtener un pdf via API ( SOLUCIONADO )

Post Reply
User avatar
Patricio Avalos Aguirre
Posts: 1069
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile
Contact:

obtener un pdf via API ( SOLUCIONADO )

Post by Patricio Avalos Aguirre »

hola a tod@s

Estimados estoy obteniendo un pdf via api, pero me responde en un formato text
necesito convertirlo a pdf pero si lo graba directo como pdf me sale error en el archivo

alguna forma de poder grabarlo a pdf

se agradece cualquier ayuda

adjunto parte del archivo que devuelve
algo asi

Code: Select all | Expand

%PDF-1.7
%����
1 0 obj
<<
/Type /Catalog
/Pages 4 0 R
/MarkInfo<</Marked true>>
/Metadata 22 0 R
/OutputIntents 24 0 R
/StructTreeRoot 5 0 R
/PageMode /UseNone
/OCProperties << /OCGs [6 0 R] /D << /ON [6 0 R] /AS [<</Event /Print /OCGs [6 0 R] /Category [/Print]>>] >> >>
>>
endobj
Last edited by Patricio Avalos Aguirre on Thu Apr 17, 2025 9:35 pm, edited 1 time in total.
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
User avatar
cnavarro
Posts: 6656
Joined: Wed Feb 15, 2012 8:25 pm
Location: España
Has thanked: 8 times
Been thanked: 10 times

Re: obtener un pdf via API

Post by cnavarro »

Hola, no sé como haces el request para obtener el fichero
Todo indica que en tu request no está definido correctamente el "Content-Type:", que es el que indica lo que se espera del request
https://developer.mozilla.org/en-US/doc ... ntent-Type
Si no te aclaras y me das un poco más de informacion respecto a como haces el request podré ayudarte mejor
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
karinha
Posts: 8055
Joined: Tue Dec 20, 2005 7:36 pm
Location: São Paulo - Brasil
Been thanked: 8 times
Contact:

Re: obtener un pdf via API

Post by karinha »

¿Te refieres a algo así?

https://www.fpdf.org/?go=script&id=75

Sinceramente no entendí tu pregunta.

Regards, saludos.
João Santos - São Paulo - Brasil - Phone: +55(11)95150-7341
User avatar
Lailton
Posts: 187
Joined: Fri Jul 20, 2012 1:49 am
Location: Brazil
Has thanked: 2 times
Been thanked: 13 times
Contact:

Re: obtener un pdf via API

Post by Lailton »

Me parece ser lo raw del PDF

Prueba con:

cBuffer es lo que te devolve

Code: Select all | Expand

hb_memoWrit( "file.pdf", cBuffer )
Patricio Avalos Aguirre wrote: Wed Apr 16, 2025 1:37 am hola a tod@s

Estimados estoy obteniendo un pdf via api, pero me responde en un formato text
necesito convertirlo a pdf pero si lo graba directo como pdf me sale error en el archivo

alguna forma de poder grabarlo a pdf

se agradece cualquier ayuda

adjunto parte del archivo que devuelve
algo asi

Code: Select all | Expand

%PDF-1.7
%����
1 0 obj
<<
/Type /Catalog
/Pages 4 0 R
/MarkInfo<</Marked true>>
/Metadata 22 0 R
/OutputIntents 24 0 R
/StructTreeRoot 5 0 R
/PageMode /UseNone
/OCProperties << /OCGs [6 0 R] /D << /ON [6 0 R] /AS [<</Event /Print /OCGs [6 0 R] /Category [/Print]>>] >> >>
>>
endobj
Regards,
Lailton Fernando Mariano
User avatar
Patricio Avalos Aguirre
Posts: 1069
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile
Contact:

Re: obtener un pdf via API

Post by Patricio Avalos Aguirre »

gracias por las respuestas

layton al procesar me genera hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseText )y abrir el pdf error al procesar página. colorSpace no válido

cnavarro, el api tambien tiene en su web para ir probando y me da lo mismo
https://docs.skualo.cl/reference/obtener-pdf-documento

https://ibb.co/kVSbgSgB

Image

gracias por su ayuda :-)
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
User avatar
Lailton
Posts: 187
Joined: Fri Jul 20, 2012 1:49 am
Location: Brazil
Has thanked: 2 times
Been thanked: 13 times
Contact:

Re: obtener un pdf via API

Post by Lailton »

para PDF te recommendo usar asi:

Code: Select all | Expand

hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseBody )
se no funcionar, prueba com asi:

Code: Select all | Expand

hb_memoWrit( "c:\paso\file.pdf", hb_strToUtf8( oHttp:ResponseBody ) )
:)
Regards,
Lailton Fernando Mariano
User avatar
Patricio Avalos Aguirre
Posts: 1069
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile
Contact:

Re: obtener un pdf via API

Post by Patricio Avalos Aguirre »

ahh se me fue la empresa me envio esta respuesta

Te recomiendo hacer la prueba desde Postman, ya que lo que devuelve la api en ese endpoint es el archivo PDF como tal.

:mrgreen:
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
User avatar
Patricio Avalos Aguirre
Posts: 1069
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile
Contact:

Re: obtener un pdf via API

Post by Patricio Avalos Aguirre »

por postman funciona bien el pdf :-(

Image
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
User avatar
cmsoft
Posts: 1316
Joined: Wed Nov 16, 2005 9:14 pm
Location: Mercedes - Bs As. Argentina
Has thanked: 2 times
Been thanked: 4 times

Re: obtener un pdf via API

Post by cmsoft »

Patricio:
Pareciera que esta todo bien y lo que te devuelve es el pdf correcto.
Como grabas luego de obtener el texto?
Con lo que te comenta Lailton creo que deberia funcionar bien

Code: Select all | Expand

  hb_memowrit('mipdf.pdf',oHttp:ResponseBody)
   shellexecute(0,"open",hb_curdrive()+":\"+CurDir()+"\mipdf.pdf",,,1)
User avatar
Lailton
Posts: 187
Joined: Fri Jul 20, 2012 1:49 am
Location: Brazil
Has thanked: 2 times
Been thanked: 13 times
Contact:

Re: obtener un pdf via API

Post by Lailton »

tiene probado asi?
Lailton wrote: Thu Apr 17, 2025 5:56 pm para PDF te recommendo usar asi:

Code: Select all | Expand

hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseBody )
se no funcionar, prueba com asi:

Code: Select all | Expand

hb_memoWrit( "c:\paso\file.pdf", hb_strToUtf8( oHttp:ResponseBody ) )
:)
Regards,
Lailton Fernando Mariano
User avatar
Patricio Avalos Aguirre
Posts: 1069
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile
Contact:

Re: obtener un pdf via API

Post by Patricio Avalos Aguirre »

Gracias !!!!
Laiton funcionooo

Code: Select all | Expand

hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseBody )
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
User avatar
Lailton
Posts: 187
Joined: Fri Jul 20, 2012 1:49 am
Location: Brazil
Has thanked: 2 times
Been thanked: 13 times
Contact:

Re: obtener un pdf via API ( SOLUCIONADO )

Post by Lailton »

8)
Regards,
Lailton Fernando Mariano
elmoiquique
Posts: 335
Joined: Wed May 16, 2007 9:40 pm
Location: Region de Ñuble, Chile
Has thanked: 1 time
Been thanked: 1 time

Re: obtener un pdf via API ( SOLUCIONADO )

Post by elmoiquique »

Hola Patricio

Podrias colocar parte del programa donde envias la consulta y la respuesta, yo estoy en lo mismo pero no logro construir el PDF

Este es mi programa, te agradeceria tu ayuda

FUNCTION RDOCLPT(TS_TOKEN)
LOCAL oHttp,Doc,cxmLbody,oIni,nHandle
LOCAL ts_exit:=.t.,tw_servidor:='',ts_mj1:='',ts_modulo:=.f.
LOCAL ts_servidor:="https://sveqa.zofri.cl/sveProcDocWSN/Emision?WSDL"

if empty(ts_token)
msginfo('Debe Obtener un Token de Inicio para Autentificarse en Web Service','Token de Sesion')
return .f.
endif

cXmlBody:= '' +;
'<?xml version="1.0" encoding="utf-8"?>' + ;
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cl="cl.zofri.sve" xmlns:wsn="http://cl/zofri/sve/prd/wsn">'+;
' <soapenv:Header>'+;
' <cl:token>'+ts_token+'</cl:token>'+;
' </soapenv:Header>'+;
' <soapenv:Body>'+;
' <wsn:emisionDocumento>'+;
' <wsn:codigoAduaneroDoc>101-25-051206</wsn:codigoAduaneroDoc>'+;
' <wsn:tipoEmision>E</wsn:tipoEmision>'+;
' </wsn:emisionDocumento>'+;
' </soapenv:Body>'+;
'</soapenv:Envelope>'

TRY
oHttp := CreateObject( 'MSXML2.XMLHTTP.6.0' )
CATCH
oHttp := CreateObject( 'Microsoft.XMLHTTP' )
END
doc = CreateObject("MSXML2.DOMDocument.6.0")

oHttp:Open( "POST" , ts_servidor, .F. )
ohttp:SetRequestHeader( "Content-Type" , "text/xml; charset=utf-8" )
oHttp:SetRequestHeader( "Connection:", "Keep-Alive" )
doc:LoadXML( cXmlbody )

TRY
ohttp:Send( doc:xml )
CATCH
cErrorMsg:='No Se Pudo Enviar Documento XML...'+CRLF+CRLF+;
'Sin Conexion a Internet o Servidor Con Problemas'
msginfo(cErrorMsg,"Intente Nuevamente")
return .t.
END
// ?ohttp:status
//status 200 = OK
// 500 = ERROR

response = ohttp:responsetext

hb_memoWrit( "fileout.pdf", oHttp:ResponseBody )

//crear un archivo para leer tag
cFilename:="texto.xml"
MEMOWRIT( cfilename, response, .F. )
//leer archivo para extraer el factura pdf
CTXT:=MEMOREAD(CFILENAME)
pdfin:=at("%PDF-1.4",CTXT)
pdfend:=At("%EOF",CTXT)
largo:=pdfend-pdfin
Cresp:=substr(CTXT,pdfin,largo+4)

//SE CREA EL ARCHIVO PDF
CPDF:="TEXTO.PDF"
MEMOWRIT( cPdf, CRESP, .F. )

RETURN .T.
Fivewin-Xharbour 24.09, Iquique, Chile
User avatar
Patricio Avalos Aguirre
Posts: 1069
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile
Contact:

Re: obtener un pdf via API ( SOLUCIONADO )

Post by Patricio Avalos Aguirre »

Hola adjunto lo solicitado

Code: Select all | Expand

cUrlSkualo := 'https://api.skualo.cl/'+_TOKENEMP_+'/documentos/'+cId+'/pdf'  //esta info es entregado por el api 

oDoc := CreateObject( "MSXML2.DOMDocument" )
oHttp := CreateObject( "MSXML2.XMLHTTP" )

	do case
	case cOpc = "A"
		ohttp:Open( "POST" ,cUrlSkualo, .F. )
	case cOpc = "M"
		ohttp:Open( 'PUT' ,cUrlSkualo, .F. )
	case cOpc = "L"
		ohttp:Open( 'GET' ,cUrlSkualo, .F. )
	otherwise
		MsgInfo( "Debe enviar Opcion " )
		return("")
endcase

if cFuncion $ "DTE;PDF"
	oHttp:SetRequestHeader("accept", "application/pdf" )
else
	oHttp:SetRequestHeader("accept", "application/json" )
	if cOpc <> "L"
		oHttp:SetRequestHeader("content-type", "application/json" )
	endif
endif

oHttp:SetRequestHeader("Authorization", "Bearer " + _TOKENEMP_ )

TRY
  oHttp:Send( jSon )
CATCH
  lOk := .f.
END

if lOk .and. oHttp:status = 200

	hb_jsonDecode( oHttp:ResponseText,@hReturn )

	if cFuncion = "GETPDF"
		cFilePdf := DRIVELOCAL+'\TEMPORAL\'+cPdf+'.pdf'
		//cPdf = tip_doc + num_doc

		hb_memowrit( cFilePdf, oHttp:ResponseBody )

		if left( cPdf,3) = "BEL"
			cPrinter := ViewUsu():Bel
		else
			cPrinter := ViewUsu():Fel
		endif

		if empty( cPrinter )
			cCmd := cSumatra + " "+cFilePdf
		else
			cCmd := cSumatra + ' -Print-to "' + alltrim( StrToken( cPrinter, 1, "," ) ) + '" -exit-on-print ' + cFilePdf
		endif

		MsgRun( "Imprimiendo archivo "+cFilePdf, "Espere..", { || winexec( cCmd, SW_HIDE )  } )

	else
		//hb_jsonDecode( oHttp:ResponseText,@hReturn )

		hReturn["status"]   	 := 200
		hReturn["statusText"] := "ok"
		hReturn["title"]   	 := "ok"
		hReturn["isError"]    := .f.
	endif

else
	if lOk // hizo la conexion pero skualo rechazo la solicitud
		hb_jsonDecode( oHttp:ResponseText,@hReturn )
		hReturn["status"]   	  := oHttp:status
		hReturn["statusText"]  := oHttp:statusText
		hReturn["title"]   	  := lower(hReturn["title"])
		hReturn["ErrorSkualo"] :=  {strtran(oHttp:ResponseText, ",", ","+CRLF ) }
		hReturn["JsonSkualo"]  :=  { json }
		hReturn["isError"]    := .t.
	else
		hReturn["status"]   	  := 400
		hReturn["title"]   	  := "error"
		hReturn["statusText"]  := "Error en la comunicación con Skualo"+CRLF+"hay q volver hacer la operación"
		hReturn["ErrorSkualo"] :=  {""}
		hReturn["JsonSkualo"]  :=  { json }
		hReturn["isError"]    := .t.
	endif
endif

return( hReturn )
//-----------------------------------------------------------------------------------------------------
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
Post Reply