2017-01-23 2 views
0

의미있는 프로젝트를 실현하고 있으며이를 해결할 방법을 찾지 못한 채 문제가 발생합니다.Django 및 API REST가 잘못된 PDF 구조

LogicalDoc에 Django (xhtml2pdf library) 덕분에 pdf file이 저장되었습니다. 나는 .. 폴더를 생성하지만 파일을 열고 자 할 때, 나는 다음과 같은 오류 메시지가 받고 있어요 :

Message : Invalid PDF structure 

이상하게도, 그것은 이전에 근무하고 지금은 작동하지 않습니다. 이 생성 된 문서에 오류가 어쩌면,하지만 어디서 찾을 수 없습니다 : 내 단말기에 오류가없는

@login_required 
def BirthCertificate_PDF(request, id) : 

    birthcertificate = get_object_or_404(BirthCertificate, pk=id) 

    data = {"birthcertificate" : birthcertificate} 

    template = get_template('BC_raw.html') 
    html = template.render(Context(data)) 


    filename_directory = str(BirthCertificate.objects.get(pk=id).id) + "_" + str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday) 
    filename = 'Acte_Naissance_' + filename_directory + '.pdf' 
    path_individus = '/Users/valentinjungbluth/Desktop/Django/Individus/' 
    path = path_individus + filename 

    print BirthCertificate.objects.get(pk=id).folderId 

    file = open(path, "w+b") 
    pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') 

    # If folderID is NULL : create a folder and save pdf file inside 
    if BirthCertificate.objects.filter(pk=id).filter(folderId__isnull=True) : 

     payload = '{{ "name":"{0}", "parentId":3309569 }}'.format(filename_directory) 

     url = 'http://localhost:8080/services/rest/folder/create' 
     headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} 
     resp = requests.post(url, data=payload, headers=headers, auth=('admin', 'admin')) 
     rbody = resp.content 
     data = json.loads(rbody) 

     folderId_person = BirthCertificate.objects.filter(pk=id).update(folderId=data["id"]) # Give the number folderId to a person 


     payload = '{{ "language":"fr","fileName":"{0}","folderId": "{1}" }}'.format(filename, BirthCertificate.objects.get(pk=id).folderId) 
     upfile = path 
     files = { 
     'document': (None, payload, 'application/json'), 
     'content': (os.path.basename(upfile), open(upfile, 'rb'), 'application/octet-stream') 
     } 
     url = 'http://localhost:8080/services/rest/document/create' 
     headers = {'Content-Type': 'multipart/form-data'} 
     r = requests.post(url, files=files, headers=headers, auth=('admin', 'admin')) 

     for element in glob.glob(path) : 
      os.remove(element) 

    #elif folderID is not null (corresponding to an existing folder), just save pdf file inside the folder. DON'T CREATE a new one. 
    elif BirthCertificate.objects.filter(pk=id).exclude(folderId__isnull=True) : 

     payload = '{{ "language":"fr","fileName":"{0}","folderId": "{1}" }}'.format(filename, BirthCertificate.objects.get(pk=id).folderId) 
     upfile = path 
     files = { 
     'document': (None, payload, 'application/json'), 
     'content': (os.path.basename(upfile), open(upfile, 'rb'), 'application/octet-stream') 
     } 
     url = 'http://localhost:8080/services/rest/document/create' 
     headers = {'Content-Type': 'multipart/form-data'} 
     r = requests.post(url, files=files, headers=headers, auth=('admin', 'admin')) 

     for element in glob.glob(path) : 
      os.remove(element) 



    file.seek(0) 
    pdf = file.read() 
    context = {"birthcertificate":birthcertificate, 
       "path":path, 
    } 

    return render(request, 'BC_PDF.html', context) 

    file.close() 

    return HttpResponse(pdf, 'application/pdf') 

,하지만 난 LogicalDoc에서 직접 PDF 파일을 찾거나있을 때 나는 그것을 다운로드 할 때 LogicalDoc에서 :

enter image description here

당신이 내 문제에 대해 어떤 생각을 가지고 있습니까? 뭔가 잘못되었다 ?

편집 :

내가 텍스트 편집기를 사용하여 내 PDF 파일을 열거야, 내가 갖는 : 올바른 시작 같이

%PDF-1.4 
%ìåãû ReportLab Generated PDF document http://www.reportlab.com 
1 0 obj 
<< /F1 2 0 R /F2 3 0 R /F3 4 0 R >> 
endobj 
2 0 obj 
<< /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> 
endobj 
3 0 obj 
<< /BaseFont /Courier-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font >> 
endobj 
4 0 obj 
<< /BaseFont /Courier /Encoding /WinAnsiEncoding /Name /F3 /Subtype /Type1 /Type /Font >> 
endobj 
5 0 obj 
<< /Contents 19 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 18 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> 
    /Type /Page >> 
endobj 
6 0 obj 
<< /Outlines 8 0 R /PageMode /UseNone /Pages 18 0 R /Type /Catalog >> 
endobj 
7 0 obj 
<< /Author() /CreationDate (D:20170125090524+00'00') /Creator (\(unspecified\)) /Keywords() /ModDate (D:20170125090524+00'00') /Producer (pisa HTML to PDF <http://www.htmltopdf.org>) 
    /Subject() /Title() /Trapped /False >> 
endobj 
8 0 obj 
<< /Count 3 /First 9 0 R /Last 9 0 R /Type /Outlines >> 
endobj 
9 0 obj 
<< /Count -1 /Dest [ 5 0 R /Fit ] /First 10 0 R /Last 10 0 R /Parent 8 0 R /Title (ACTE DE NAISSANCE COPIE INTEGRALE ) >> 
endobj 
10 0 obj 
<< /Count -7 /Dest [ 5 0 R /Fit ] /First 11 0 R /Last 17 0 R /Parent 9 0 R /Title (ACTE DE NAISSANCE COPIE INTEGRALE ) >> 
endobj 
11 0 obj 
<< /Dest [ 5 0 R /Fit ] /Next 12 0 R /Parent 10 0 R /Title (ACTE DE NAISSANCE N\260 1/2017 Arnaud LOTUS) >> 
endobj 
12 0 obj 
<< /Dest [ 5 0 R /Fit ] /Next 13 0 R /Parent 10 0 R /Prev 11 0 R /Title (Informations concernant l'enfant :) >> 
endobj 
13 0 obj 
<< /Dest [ 5 0 R /Fit ] /Next 14 0 R /Parent 10 0 R /Prev 12 0 R /Title (Informations sur le p\350re :) >> 
endobj 
14 0 obj 
<< /Dest [ 5 0 R /Fit ] /Next 15 0 R /Parent 10 0 R /Prev 13 0 R /Title (Informations sur la m\350re :) >> 
endobj 
15 0 obj 
<< /Dest [ 5 0 R /Fit ] /Next 16 0 R /Parent 10 0 R /Prev 14 0 R /Title (Par la pr\351sente, l'officier d'Etat Civil certifie la conformit\351 de la d\351claration) >> 
endobj 
16 0 obj 
<< /Dest [ 5 0 R /Fit ] /Next 17 0 R /Parent 10 0 R /Prev 15 0 R /Title (L'Officier d'Etat Civil ) >> 
endobj 
17 0 obj 
<< /Dest [ 5 0 R /Fit ] /Parent 10 0 R /Prev 16 0 R /Title (Signature et tampon ) >> 
endobj 
18 0 obj 
<< /Count 1 /Kids [ 5 0 R ] /Type /Pages >> 
endobj 
19 0 obj 
<< /Filter [ /ASCII85Decode /FlateDecode ] /Length 1351 >> 
stream 
Gb!;e?#u`2'RdI5s)?lTClKJ3K.l+Q6F'@s-;h&Z>[email protected]>oACs5i!m]$9TA*b4\='"WSR'C$!i2=/\`]Q2)C]@pU#e17!F0kgISGAKn3We"#k02!HMu^XrSDt5V4/(@,$Yu%!7TrG'"WeWCDTeadd9'3\0_V'^=N&KG'"Z(UI84Kl/8[oBp<S->Bnk+!`aHK9O.gCIa-A^H!OO4eKB3lJTL(dE94sd):.Kko[<[<hHp9>045D4Wc>Y>CN+QG2g/Ulp"Z%)1T<!*PM-jT25qKNA/_%Ieg:G%_>Q.mpHQZLRDbbg^P)hG26N\[email protected]\[email protected];4+NEt!>2k"4-D/T>/1n/0U/]u-OU"_\4KJk(^[email protected]"73R1XI9lRDV?S>i.lTNJ8bT%\[email protected];:M`nuS-[>B/;b(iHaCIE)O`bFXsP;(6^IM&DJ%RHNd'%'A[LsKTEWh%PBO><<P#"WNl>"%NgG"P1]OP),AD3R+aepf*#qGC:"-5JSL&r!g#1RP$i=N[1)YB+HgS`W`sW(u]6r;BEb\B>XmVb+I'%._Am4]JG5CCc?CLs\qO\9S+363\31BF)T4RlU(ugP=Gk%,p2e\h<oV2))UQ'@BOg9I,[email protected]%Uc9O$0:Bt9VO#jG([email protected],@/)t\]1sq)YgRRO-+-u<F2gRjRScAl8Lp<eo>dg;lINgD)[email protected]]BT'QEY!#LJYiQ]#S1C3^PT)>)u962r?bla&5.77dV)[email protected]=r<"OXg&"[email protected]]1j0"o*i:k4P6^PXp`3!Q.?5ds$T(g-<]?jc>3]n)[email protected]$#^9/Yjk3=jGHn%1[PdY"QA14"=e%^8qnEX77iOP>\[email protected]]+1hS,HbPBKqlY0p;a6uc2CiNH8Ye_!C5f!9C555Z#77iD3ip>G.H=#Hd[19_T4-IjpefjW!lhuq%*d8_3,^WERY(q%[email protected][PMD-7l-]_h'MU86.2C="pHNj'``^Hbl3Bu>eponLI9Xr?'kU&l-2("nNRlRuud(*acqr6Q]B"XUj;S!KDfb+Xc3r4G)ABL1Ap4*[email protected]+ERA-*_[>Cu#$_#hKqK]?,eWc&cm^G?$YH%>fIU,gV2jLG6`^P.([N)-rL;<@LjZlFCsm,[email protected]#ZY"D3:&TNa%1;_r&A&BjuZ&8OmfD<^)VXg^(k0D:&BN6qP'#FJOnQ?cb=JFHTQ=k*o(N:7?M.-a$<^^@q/fK>KZp>X.Wtl>u)Ed`";XodS6B(N%s).e"<8_;bs*l>^+I:$k%JSaRbiJ-a[3WC]][email protected]$#?DQ8VDVp)*Db&[email protected]:9tr7+`Wo<,)OcRY%VrSDaXpd7[~>endstream 
endobj 
xref 
0 20 
0000000000 65535 f 
0000000075 00000 n 
0000000129 00000 n 
0000000239 00000 n 
0000000352 00000 n 
0000000460 00000 n 
0000000669 00000 n 
0000000757 00000 n 
0000001005 00000 n 
0000001079 00000 n 
0000001220 00000 n 
0000001362 00000 n 
0000001492 00000 n 
0000001624 00000 n 
0000001751 00000 n 
0000001878 00000 n 
0000002066 00000 n 
0000002188 00000 n 
0000002293 00000 n 
0000002356 00000 n 
trailer 
<< /ID 
% ReportLab generated PDF document -- digest (http://www.reportlab.com) 
[(Q:l\305\243:\334M\275B\203\250\311\260ug) (Q:l\305\243:\334M\275B\203\250\311\260ug)] 
/Info 7 0 R /Root 6 0 R /Size 20 >> 
startxref 
3804 
%%EOF 
+0

Blind는 생성 된 출력에 다른 데이터가 포함되어 있으므로 텍스트 편집기로 열어 머리를 봅니다. – Cyrbil

+0

정확히 어떤 파일을 텍스트 편집기로 열어야합니까? 내 PDF 파일? – Deadpool

+0

예, PDF 파일 – Cyrbil

답변

1

PDF 파일에 (정확하고 end %PDF-1.4 ... %%EOF 코드에 약간의 오류가 있습니다. 귀하의 기능에 2 return 문이 표시됩니다. 아마 리팩토링에 대한 몇 가지 테스트 결과가 표시 될 수 있습니다.

또한 y 우리가 열어 본 파일은 반환 트리거가 처음 발생한 이후로 파일에 대해 with 문을 사용하고 파일을 엄격한 최소 시간 (열린 상태, 읽은 상태, 닫힌 상태)으로 열어 두는 것이 좋으며, 읽기 전에 파일과 아무 관련이없는 많은 것들이 있습니다 그것.

마지막으로 코드 확인을 pep8 실행하면 곧 또는 나중에 문제가 될 많은 오류가 표시됩니다 (return 문제가 즉시 발생합니다).